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" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
611
module SCIP import LinearAlgebra import OpenBLAS32_jll # assorted utility functions include("util.jl") # load deps, version check include("init.jl") # wrapper of SCIP library include("wrapper.jl") # memory management include("scip_data.jl") include("sepa.jl") include("cut_selector.jl") include("heuristic.jl") include("branching_rule.jl") # constraint handlers include("conshdlr.jl") # constraints from nonlinear expressions include("nonlinear.jl") # implementation of MOI include("MOI_wrapper.jl") # convenience functions include("convenience.jl") # warn about rewrite include("compat.jl") end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
7914
# branching rule interface # it is recommended to check https://scipopt.org/doc/html/BRANCH.php for key concepts and interface """ Abstract class for branching rule. A branching rule must implement the `branch` method. It also stores all user data that must be available to select a branching variable. """ abstract type AbstractBranchingRule end """ The type of solution we branch on. The three subtypes are BranchingLP, BranchingPseudoSolution, BranchingExternalCandidate """ abstract type BranchingType end """ Branching for LP candidate, corresponds to the SCIP `SCIP_DECL_BRANCHEXECLP` callback. """ struct BranchingLP <: BranchingType end """ Branching for pseudo-solution candidate, corresponds to the SCIP `SCIP_DECL_BRANCHEXECPS` callback. """ struct BranchingPseudoSolution <: BranchingType end """ Branching for external candidate, corresponds to the SCIP `SCIP_DECL_BRANCHEXECEXT` callback. """ struct BranchingExternalCandidate <: BranchingType end """ branch(branching_rule, scip, allow_additional_constraints, type) Perform branching with the current `branching_rule`. `allow_additional_constraints` is a Boolean indicating if the branching rule is allowed to add constraints to the current node in order to cut off the current solution instead of creating a branching. That method must return a tuple (return_code::LibSCIP.SCIP_RETCODE, result::SCIP.LibSCIP.SCIP_RESULT). If no branching was performed, use `SCIP_DIDNOTRUN` as a result to pass on to the following branching rule. `type` is the `BranchingType` to branch on, i.e. on LP solution, pseudo-solution or external candidate. """ function branch(branching_rule::AbstractBranchingRule, scip, allow_additional_constraints, type::BranchingType) return (LibSCIP.SCIP_OKAY, LibSCIP.SCIP_DIDNOTRUN) end """ get_branching_candidates(scip) returns a tuple with branching candidate information, including: `(candidates, candidates_values, candidates_fractionalities, npriolpcands, nfracimplvars)` with: - `candidates` a vector of variables with the branching candidates - `candidates_values` the corresponding values at the LP relaxation - `candidates_fractionalities` the corresponding fractionalities - `npriolpcands` the number of candidates with maximal priority that MUST be branched on - `nfracimplvars` the number of fractional implicit integer variables, that should not be branched on. """ function get_branching_candidates(scip) lpcands = Ref{Ptr{Ptr{SCIP_VAR}}}(C_NULL) lpcandssol = Ref{Ptr{SCIP_Real}}(C_NULL) lpcandsfrac = Ref{Ptr{SCIP_Real}}(C_NULL) nlpcands = Ref{Cint}(-1) npriolpcands = Ref{Cint}(-1) nfracimplvars = Ref{Cint}(-1) @SCIP_CALL SCIPgetLPBranchCands( scip, lpcands, lpcandssol, lpcandsfrac, nlpcands, npriolpcands, nfracimplvars, ) @assert lpcands[] != C_NULL @assert nlpcands[] > 0 @assert npriolpcands[] >= 0 candidates = unsafe_wrap(Array, lpcands[], nlpcands[]) @assert lpcandssol[] != C_NULL candidates_values = unsafe_wrap(Array, lpcandssol[], nlpcands[]) @assert lpcandsfrac[] != C_NULL candidates_fractionalities = unsafe_wrap(Array, lpcandsfrac[], nlpcands[]) @assert nfracimplvars[] >= 0 return ( candidates, candidates_values, candidates_fractionalities, npriolpcands[], nfracimplvars[], ) end function branch_on_candidate!(scip, var) @SCIP_CALL LibSCIP.SCIPbranchVar(scip, var, C_NULL, C_NULL, C_NULL) return nothing end function _branchrulefree(::Ptr{SCIP_}, branching::Ptr{SCIP_BRANCHRULE}) # just like sepa, free the data on the SCIP side, # the Julia GC will take care of the objects SCIPbranchruleSetData(branching, C_NULL) return SCIP_OKAY end ##### # Low-level SCIP callbacks ## These are defined here to match the C function signature expected by SCIP ##### function _branchrule_exec_lp(scip::Ptr{SCIP_}, branchrule_::Ptr{SCIP_BRANCHRULE}, allowaddcons::SCIP_Bool, result_::Ptr{SCIP_RESULT}) branchruledata::Ptr{SCIP_BRANCHRULEDATA} = SCIPbranchruleGetData(branchrule_) branchrule = unsafe_pointer_to_objref(branchruledata) (retcode, result) = branch(branchrule, scip, allowaddcons == 1, BranchingLP())::Tuple{SCIP_RETCODE,SCIP_RESULT} if retcode != SCIP_OKAY return retcode end unsafe_store!(result_, result) return retcode end function _branchrule_exec_ps(scip::Ptr{SCIP_}, branchrule_::Ptr{SCIP_BRANCHRULE}, allowaddcons::SCIP_Bool, result_::Ptr{SCIP_RESULT}) branchruledata::Ptr{SCIP_BRANCHRULEDATA} = SCIPbranchruleGetData(branchrule_) branchrule = unsafe_pointer_to_objref(branchruledata) (retcode, result) = branch(branchrule, scip, allowaddcons == 1, BranchingPseudoSolution())::Tuple{SCIP_RETCODE,SCIP_RESULT} if retcode != SCIP_OKAY return retcode end unsafe_store!(result_, result) return retcode end function _branchrule_exec_external(scip::Ptr{SCIP_}, branchrule_::Ptr{SCIP_BRANCHRULE}, allowaddcons::SCIP_Bool, result_::Ptr{SCIP_RESULT}) branchruledata::Ptr{SCIP_BRANCHRULEDATA} = SCIPbranchruleGetData(branchrule_) branchrule = unsafe_pointer_to_objref(branchruledata) (retcode, result) = branch(branchrule, scip, allowaddcons == 1, BranchingExternalCandidate())::Tuple{SCIP_RETCODE,SCIP_RESULT} if retcode != SCIP_OKAY return retcode end unsafe_store!(result_, result) return retcode end """ Includes a branching rule in SCIP and stores it in branchrule_storage. Keyword of interests can be: `maxdepth` corresponding to SCIP `BRANCHRULE_MAXDEPTH`. Use -1 for no depth limit, `max_bound_distance` corresponding to `BRANCHRULE_MAXBOUNDDIST`. """ function include_branchrule( scip::Ptr{SCIP_}, branchrule::BR, branchrule_storage::Dict{Any,Ptr{SCIP_BRANCHRULE}}; name="", description="", priority=10000, maxdepth=-1, max_bound_distance=1.0, ) where {BR<:AbstractBranchingRule} # ensure a unique name for the cut selector if name == "" name = "branchrule_$(string(BR))" end branchrule__ = Ref{Ptr{SCIP_BRANCHRULE}}(C_NULL) if !ismutable(branchrule) throw( ArgumentError("The branching rule structure must be a mutable type"), ) end branchruledata_ = pointer_from_objref(branchrule) branchrule_callback_lp = @cfunction( _branchrule_exec_lp, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_BRANCHRULE}, SCIP_Bool, Ptr{SCIP_RESULT}, ), ) branchrule_callback_ps = @cfunction( _branchrule_exec_ps, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_BRANCHRULE}, SCIP_Bool, Ptr{SCIP_RESULT}, ), ) branchrule_callback_ext = @cfunction( _branchrule_exec_external, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_BRANCHRULE}, SCIP_Bool, Ptr{SCIP_RESULT}, ), ) @SCIP_CALL SCIPincludeBranchruleBasic( scip, branchrule__, name, description, priority, maxdepth, max_bound_distance, branchruledata_, ) @assert branchrule__[] != C_NULL @SCIP_CALL SCIPsetBranchruleFree( scip, branchrule__[], @cfunction(_branchrulefree, SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_BRANCHRULE})), ) @SCIP_CALL SCIPsetBranchruleExecLp( scip, branchrule__[], branchrule_callback_lp, ) @SCIP_CALL SCIPsetBranchruleExecPs( scip, branchrule__[], branchrule_callback_ps, ) @SCIP_CALL SCIPsetBranchruleExecExt( scip, branchrule__[], branchrule_callback_ext, ) # store branching rule (avoids GC-ing it) branchrule_storage[branchrule] = branchrule__[] end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
268
export SCIPSolver # dummy implementation to tell users about transition to MathOptInterface function SCIPSolver(args...; kwargs...) error( "Support for MathProgBase was dropped. " * "Please downgrade to v0.6.1, see README for details.", ) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
15781
# # Wrappers for implementing SCIP constraint handlers in Julia. # # Please study the corresponding SCIP documentation first, to become familiar # with basic concepts and terms: https://www.scipopt.org/doc/html/CONS.php # # The basic idea is that you create a new subtype of `AbstractConstraintHandler` # to store the constraint handler data and implement the fundamental callbacks # by adding methods to the functions `check`, `enforce_lp_sol`, # `enforce_pseudo_sol` and `lock`. # # If your constraint handler uses constraint objects (`needs_constraints`), you # create a subtype of the parametrized `AbstractConstraint`. # # # Current limitations: # - We now use fixed values for some properties: # - SEPAPRIORITY = 0 # - SEPAFREQ = -1 # - DELAYSEPA = FALSE # - PROPFREQ = -1 # - DELAYPROP = -1 # - PROP_TIMING = SCIP_PROPTIMING_BEFORELP # - PRESOLTIMING = SCIP_PRESOLTIMING_MEDIUM # - MAXPREROUNDS = -1 # - We don't support these optional methods: CONSHDLRCOPY, CONSFREE, CONSINIT, # CONSEXIT, CONSINITPRE, CONSEXITPRE, CONSINITSOL, CONSEXITSOL, CONSDELETE, # CONSTRANS, CONSINITLP, CONSSEPALP, CONSSEPASOL, CONSENFORELAX, CONSPROP, # CONSPRESOL, CONSRESPROP, CONSACTIVE, CONSDEACTIVE, CONSENABLE, CONSDISABLE, # CONSDELVARS, CONSPRINT, CONSCOPY, CONSPARSE, CONSGETVARS, CONSGETNVARS, # CONSGETDIVEBDCHGS # - We don't support linear or nonlinear constraint upgrading. # # # Abstract Supertypes: # """ AbstractConstraintHandler Abstract supertype for objects that store all user data belonging to the constraint handler. This object is also used for method dispatch with the callback functions. From SCIP's point-of-view, this objects corresponds to the SCIP_CONSHDLRDATA, but its memory is managed by Julia's GC. It's recommended to store a reference to your instance of `SCIP.Optimizer` here so that you can use it within your callback methods. """ abstract type AbstractConstraintHandler end """ AbstractConstraint{Handler} Abstract supertype for objects that store all user data belonging to an individual constraint. It's parameterized by the type of constraint handler. From SCIP's point-of-view, this objects corresponds to the SCIP_CONSDATA, but its memory is managed by Julia's GC. """ abstract type AbstractConstraint{Handler} end # # Fundamental Callbacks for Julia. # """ check( constraint_handler::CH, constraints::Array{Ptr{SCIP_CONS}}, sol::Ptr{SCIP_SOL}, checkintegrality::Bool, checklprows::Bool, printreason::Bool, completely::Bool )::SCIP_RESULT Check whether the solution candidate given by `sol` satisfies all constraints in `constraints`. Use the functions `user_constraint` and `sol_values` to access your constraint-specific user data and solution values, respectively. Acceptable result values are: * `SCIP_FEASIBLE`: The solution candidate satisfies all constraints. * `SCIP_INFEASIBLE`: The solution candidate violates at least one constraint. There is nothing else to do for the user in terms of dealing with the violation. """ function check end """ enforce_lp_sol( constraint_handler::CH, constraints::Array{Ptr{SCIP_CONS}}, nusefulconss::Cint, solinfeasible::Bool )::SCIP_RESULT Enforce the current solution for the LP relaxation. That is, check all given constraints for violation and deal with it in some way (see below). Use the functions `user_constraint` and `sol_values` to access your constraint-specific user data and solution values, respectively. Acceptable result values are: * `SCIP_FEASIBLE`: The solution candidate satisfies all constraints. * `SCIP_CUTOFF`: The current subproblem is infeasible. * `SCIP_CONSADDED`: Added a constraint that resolves the infeasibility. * `SCIP_REDUCEDDOM`: Reduced the domain of a variable. * `SCIP_SEPARATED`: Added a cutting plane. * `SCIP_BRANCHED`: Performed a branching. * `SCIP_INFEASIBLE`: The solution candidate violates at least one constraint. """ function enforce_lp_sol end """ enforce_pseudo_sol( constraint_handler::CH, constraints::Array{Ptr{SCIP_CONS}}, nusefulconss::Cint, solinfeasible::Bool )::SCIP_RESULT Enforce the current pseudo solution (the LP relaxation was not solved). That is, check all given constraints for violation and deal with it in some way (see below). Use the functions `user_constraint` and `sol_values` to access your constraint-specific user data and solution values, respectively. Acceptable result values are: * `SCIP_FEASIBLE`: The solution candidate satisfies all constraints. * `SCIP_CUTOFF`: The current subproblem is infeasible. * `SCIP_CONSADDED`: Added a constraint that resolves the infeasibility. * `SCIP_REDUCEDDOM`: Reduced the domain of a variable. * `SCIP_SEPARATED`: Added a cutting plane. * `SCIP_BRANCHED`: Performed a branching. * `SCIP_SOLVELP`: Force the solving of the LP relaxation. * `SCIP_INFEASIBLE`: The solution candidate violates at least one constraint. """ function enforce_pseudo_sol end """ lock( constraint_handler::CH, constraint::Ptr{SCIP_CONS}, locktype::SCIP_LOCKTYPE, nlockspos::Cint, nlocksneg::Cint ) Define the variable locks that the given constraint implies. For each related variable, call `SCIPaddVarLocksType` to let SCIP know whether rounding the value up or down might lead to constraint violation. """ function lock end # # Fundamental callback functions with SCIP's C API. # # There is only a single, generic implementation for each of these, which are # passed to all user-defined SCIP constraint handlers, but they will call the # user's method in the function body. # """ Generic `check` function, matching the signature from SCIP's C API. """ function _conscheck( scip::Ptr{SCIP_}, conshdlr::Ptr{SCIP_CONSHDLR}, conss::Ptr{Ptr{SCIP_CONS}}, nconss::Cint, sol::Ptr{SCIP_SOL}, checkintegrality::SCIP_Bool, checklprows::SCIP_Bool, printreason::SCIP_Bool, completely::SCIP_Bool, result::Ptr{SCIP_RESULT}, ) # get Julia object out of constraint handler data conshdlrdata::Ptr{SCIP_CONSHDLRDATA} = SCIPconshdlrGetData(conshdlr) constraint_handler = unsafe_pointer_to_objref(conshdlrdata) # get Julia array from C pointer constraints = unsafe_wrap(Vector{Ptr{SCIP_CONS}}, conss, nconss) # call user method via dispatch res = check( constraint_handler, constraints, sol, convert(Bool, checkintegrality), convert(Bool, checklprows), convert(Bool, printreason), convert(Bool, completely), ) unsafe_store!(result, res) return SCIP_OKAY end """ Generic `enfolp` function, matching the signature from SCIP's C API. """ function _consenfolp( scip::Ptr{SCIP_}, conshdlr::Ptr{SCIP_CONSHDLR}, conss::Ptr{Ptr{SCIP_CONS}}, nconss::Cint, nusefulconss::Cint, solinfeasible::SCIP_Bool, result::Ptr{SCIP_RESULT}, ) # get Julia object out of constraint handler data conshdlrdata::Ptr{SCIP_CONSHDLRDATA} = SCIPconshdlrGetData(conshdlr) constraint_handler = unsafe_pointer_to_objref(conshdlrdata) # get Julia array from C pointer constraints = unsafe_wrap(Vector{Ptr{SCIP_CONS}}, conss, nconss) # call user method via dispatch res = enforce_lp_sol( constraint_handler, constraints, nusefulconss, convert(Bool, solinfeasible), ) unsafe_store!(result, res) return SCIP_OKAY end """ Generic `enfops` function, matching the signature from SCIP's C API. """ function _consenfops( scip::Ptr{SCIP_}, conshdlr::Ptr{SCIP_CONSHDLR}, conss::Ptr{Ptr{SCIP_CONS}}, nconss::Cint, nusefulconss::Cint, solinfeasible::SCIP_Bool, objinfeasible::SCIP_Bool, result::Ptr{SCIP_RESULT}, ) # get Julia object out of constraint handler data conshdlrdata::Ptr{SCIP_CONSHDLRDATA} = SCIPconshdlrGetData(conshdlr) constraint_handler = unsafe_pointer_to_objref(conshdlrdata) # get Julia array from C pointer constraints = unsafe_wrap(Vector{Ptr{SCIP_CONS}}, conss, nconss) # call user method via dispatch res = enforce_pseudo_sol( constraint_handler, constraints, nusefulconss, convert(Bool, solinfeasible), convert(Bool, objinfeasible), ) unsafe_store!(result, res) return SCIP_OKAY end """ Generic `lock` function, matching the signature from SCIP's C API. """ function _conslock( scip::Ptr{SCIP_}, conshdlr::Ptr{SCIP_CONSHDLR}, cons::Ptr{SCIP_CONS}, locktype::SCIP_LOCKTYPE, nlockspos::Cint, nlocksneg::Cint, ) # get Julia object out of constraint handler data conshdlrdata::Ptr{SCIP_CONSHDLRDATA} = SCIPconshdlrGetData(conshdlr) constraint_handler = unsafe_pointer_to_objref(conshdlrdata) # call user method via dispatch lock(constraint_handler, cons, locktype, nlockspos, nlocksneg) return SCIP_OKAY end # # Additional callback functions for memory management. # # The implementation should work for all constraint handlers defined in Julia, # so there is no method for the user to implement. # """ Generic `free` function, matching the signature from SCIP's C API. """ function _consfree(scip::Ptr{SCIP_}, conshdlr::Ptr{SCIP_CONSHDLR}) # Here, we should free the constraint handler data. But because this is an # object created and owned by Julia, we will let GC do it. # Instead, we will just set the pointer to NULL, so that SCIP will think # that it is taken care of. SCIPconshdlrSetData(conshdlr, C_NULL) return SCIP_OKAY end """ Generic `delete` function, matching the signature from SCIP's C API. """ function _consdelete( scip::Ptr{SCIP_}, conshdlr::Ptr{SCIP_CONSHDLR}, cons::Ptr{SCIP_CONS}, consdata::Ptr{Ptr{SCIP_CONSDATA}}, ) # Here, we should free the constraint data. But because this is an object # created and owned by Julia, we will let GC do it. # Instead, we will just set the pointer to NULL, so that SCIP will think # that it is taken care of. unsafe_store!(consdata, C_NULL) return SCIP_OKAY end # # Adding constraint handlers and constraints to SCIP. # """ include_conshdlr( scip::Ptr{SCIP_}, conshdlrs::Dict{Any, Ptr{SCIP_CONSHDLR}}, ch::CH; name::String, description::String, enforce_priority::Int, check_priority::Int, eager_frequency::Int, needs_constraints::Bool ) Include a user defined constraint handler `ch` to the SCIP instance `scip`. All parameters have default values that can be set as keyword arguments. In particular, note the boolean `needs_constraints`: * If set to `true`, then the callbacks are only called for the constraints that were added explicitly using `add_constraint`. * If set to `false`, the callback functions will always be called, even if no corresponding constraint was added. It probably makes sense to set `misc/allowdualreds` to `FALSE` in this case. """ function include_conshdlr( scip::Ptr{SCIP_}, conshdlrs::Dict{Any,Ptr{SCIP_CONSHDLR}}, ch::CH; name="", description="", enforce_priority=-15, check_priority=-7000000, eager_frequency=100, needs_constraints=true, ) where {CH<:AbstractConstraintHandler} # Get C function pointers from Julia functions _enfolp = @cfunction( _consenfolp, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_CONSHDLR}, Ptr{Ptr{SCIP_CONS}}, Cint, Cint, SCIP_Bool, Ptr{SCIP_RESULT}, ) ) _enfops = @cfunction( _consenfops, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_CONSHDLR}, Ptr{Ptr{SCIP_CONS}}, Cint, Cint, SCIP_Bool, SCIP_Bool, Ptr{SCIP_RESULT}, ) ) _check = @cfunction( _conscheck, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_CONSHDLR}, Ptr{Ptr{SCIP_CONS}}, Cint, Ptr{SCIP_SOL}, SCIP_Bool, SCIP_Bool, SCIP_Bool, SCIP_Bool, Ptr{SCIP_RESULT}, ) ) _lock = @cfunction( _conslock, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_CONSHDLR}, Ptr{SCIP_CONS}, SCIP_LOCKTYPE, Cint, Cint, ) ) # Store pointer to SCIP structure (for future C API calls) conshdlr__ = Ref{Ptr{SCIP_CONSHDLR}}(C_NULL) # Hand over Julia object as constraint handler data: conshdlrdata_ = pointer_from_objref(ch) # Try to create unique name, or else SCIP will complain! if name == "" name = "__ch__$(length(conshdlrs))" end # Register constraint handler with SCIP instance. @SCIP_CALL SCIPincludeConshdlrBasic( scip, conshdlr__, name, description, enforce_priority, check_priority, eager_frequency, needs_constraints, _enfolp, _enfops, _check, _lock, conshdlrdata_, ) # Sanity checks @assert conshdlr__[] != C_NULL # Set additional callbacks. @SCIP_CALL SCIPsetConshdlrFree( scip, conshdlr__[], @cfunction(_consfree, SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_CONSHDLR})) ) @SCIP_CALL SCIPsetConshdlrDelete( scip, conshdlr__[], @cfunction( _consdelete, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_CONSHDLR}, Ptr{SCIP_CONS}, Ptr{Ptr{SCIP_CONSDATA}}, ) ) ) # Register constraint handler (for GC-protection and mapping). conshdlrs[ch] = conshdlr__[] end """ add_constraint( scipd::SCIPData, ch::CH, c::C; initial=true, separate=true, enforce=true, check=true, propagate=true, _local=false, modifiable=false, dynamic=false, removable=false, stickingatnode=false )::ConsRef Add constraint `c` belonging to user-defined constraint handler `ch` to model. Returns constraint reference. All keyword arguments are passed to the `SCIPcreateCons` call. """ function add_constraint( scipd::SCIPData, ch::CH, c::C; initial=true, separate=true, enforce=true, check=true, propagate=true, _local=false, modifiable=false, dynamic=false, removable=false, stickingatnode=false, ) where {CH<:AbstractConstraintHandler,C<:AbstractConstraint{CH}} # Find matching SCIP constraint handler plugin. conshdlr_::Ptr{SCIP_CONSHDLR} = get(scipd.conshdlrs, ch, C_NULL) conshdlr_ != C_NULL || error("No matching constraint handler registered!") # Hand over Julia object as constraint data: consdata_ = pointer_from_objref(c) # Create SCIP constraint (and attach constraint data). cons__ = Ref{Ptr{SCIP_CONS}}(C_NULL) @SCIP_CALL SCIPcreateCons( scipd, cons__, "", conshdlr_, consdata_, initial, separate, enforce, check, propagate, _local, modifiable, dynamic, removable, stickingatnode, ) # Sanity check. @assert cons__[] != C_NULL # Register constraint data (for GC-protection). scipd.conshdlrconss[c] = cons__[] # Add constraint to problem. @SCIP_CALL SCIPaddCons(scipd, cons__[]) # Register constraint and return reference. return store_cons!(scipd, cons__) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
536
## Related to constraint handlers """ Recover Julia object which is attached to user constraint (via constraint data). """ function user_constraint(cons_::Ptr{SCIP_CONS}) @assert cons_ != C_NULL consdata_::Ptr{SCIP.SCIP_CONSDATA} = SCIPconsGetData(cons_) return unsafe_pointer_to_objref(consdata_) end """ Extract solution values for given variables. """ function sol_values( o::Optimizer, vars::AbstractArray{VI}, sol::Ptr{SCIP_SOL}=C_NULL, ) return [SCIPgetSolVal(o, sol, var(o, vi)) for vi in vars] end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
8176
# cut selection interface # it is recommended to check https://scipopt.org/doc/html/CUTSEL.php for key concepts and interface """ Abstract class for cut selector. A cut selector must implement `select_cuts`. It also stores all user data that must be available to select cuts. """ abstract type AbstractCutSelector end """ select_cuts( cutsel::AbstractCutSelector, scip::Ptr{SCIP_}, cuts::Vector{Ptr{SCIP_ROW}}, forced_cuts::Vector{Ptr{SCIP_ROW}}, root::Bool, maxnslectedcuts::Integer ) -> (retcode, nselectedcuts, result) It must operate the selection of cuts by placing the selected cuts first in the selected cut vector. `nselectedcuts` must be the number of selected cuts, retcode indicates whether the selection went well. A typical result would be `SCIP_SUCCESS`, and retcode `SCIP_OKAY`. `forced_cuts` is a vector of cuts that will be added to the problem, they should not be tampered with by the function. """ function select_cuts(cutsel, scip, cuts, forced_cuts, root, maxnslectedcuts) end function _select_cut_callback( scip::Ptr{SCIP_}, cutsel_::Ptr{SCIP_CUTSEL}, cuts_::Ptr{Ptr{SCIP_ROW}}, ncuts::Cint, forced_cuts_::Ptr{Ptr{SCIP_ROW}}, nforced_cuts::Cint, root_::SCIP_Bool, maxnslectedcuts::Cint, nselectedcuts_::Ptr{Cint}, result_::Ptr{SCIP_RESULT}, ) cutseldata::Ptr{SCIP_CUTSELDATA} = SCIPcutselGetData(cutsel_) cutsel = unsafe_pointer_to_objref(cutseldata) cuts = unsafe_wrap(Vector{Ptr{SCIP_ROW}}, cuts_, ncuts) @assert length(cuts) == ncuts forced_cuts = unsafe_wrap(Vector{Ptr{SCIP_ROW}}, forced_cuts_, nforced_cuts) @assert length(forced_cuts) == nforced_cuts root = root_ == SCIP.TRUE (retcode, nselectedcuts, result) = select_cuts( cutsel, scip, cuts, forced_cuts, root, maxnslectedcuts, )::Tuple{SCIP_RETCODE,Integer,SCIP_RESULT} if retcode != SCIP_OKAY return retcode end if nselectedcuts > maxnslectedcuts error( "$nselectedcuts cuts selected by cut selected, maximum $maxnslectedcuts allowed", ) end unsafe_store!(nselectedcuts_, Cint(nselectedcuts)) unsafe_store!(result_, result) return retcode end function _cutselfree(::Ptr{SCIP_}, cutsel::Ptr{SCIP_CUTSEL}) # just like sepa, free the data on the SCIP side, # the Julia GC will take care of the objects SCIPcutselSetData(cutsel, C_NULL) return SCIP_OKAY end """ Includes a cut selector in SCIP and stores it in cutsel_storage. """ function include_cutsel( scip::Ptr{SCIP_}, cutsel::CS, cutsel_storage::Dict{Any,Ptr{SCIP_CUTSEL}}; name="", description="", priority=10000, ) where {CS<:AbstractCutSelector} # ensure a unique name for the cut selector if name == "" name = "cutselector_$(string(CS))" end cutsel__ = Ref{Ptr{SCIP_CUTSEL}}(C_NULL) if !ismutable(cutsel) throw( ArgumentError("The cut selector structure must be a mutable type"), ) end cutseldata_ = pointer_from_objref(cutsel) cutselselect_callback = @cfunction( _select_cut_callback, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_CUTSEL}, Ptr{Ptr{SCIP_ROW}}, Cint, Ptr{Ptr{SCIP_ROW}}, Cint, SCIP_Bool, Cint, Ptr{Cint}, Ptr{SCIP_RESULT}, ), ) @SCIP_CALL SCIPincludeCutselBasic( scip, cutsel__, name, description, priority, cutselselect_callback, cutseldata_, ) @assert cutsel__[] != C_NULL @SCIP_CALL SCIPsetCutselFree( scip, cutsel__[], @cfunction(_cutselfree, SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_CUTSEL})), ) # store cut selector (avoids GC-ing it) cutsel_storage[cutsel] = cutsel__[] end """ Extracts information from a SCIP_ROW into a form: `lhs ≤ aᵀ x + b ≤ rhs` The row is returned as a named tuple """ function get_row_information(scip::SCIPData, row::Ptr{SCIP_ROW}) rhs = SCIProwGetRhs(row) lhs = SCIProwGetLhs(row) b = SCIProwGetConstant(row) n = SCIProwGetNNonz(row) a_ptr = SCIProwGetVals(row) a = unsafe_wrap(Vector{Cdouble}, a_ptr, n) col_ptr = SCIProwGetCols(row) cols = unsafe_wrap(Vector{Ptr{SCIP_COL}}, col_ptr, n) x = map(cols) do col var_ptr = SCIPcolGetVar(col) var_ref = findfirst(==(var_ptr), scip.vars) @assert var_ref !== nothing var_ref end return (; rhs, lhs, b, a, x) end """ Utility function to get scores from cut that can be used to evaluate it. Returns a named tuple with three commonly used scores `(; integer_support, efficacy, objective_parallelism)`. """ function get_row_scores(scip::Ptr{SCIP_}, row::Ptr{SCIP_ROW}) integer_support = SCIPgetRowNumIntCols(scip, row) / SCIProwGetNNonz(row) efficacy = SCIPgetCutEfficacy(scip, C_NULL, row) objective_parallelism = SCIPgetRowObjParallelism(scip, cuts[i]) return (; integer_support, efficacy, objective_parallelism) end """ Composed cut selector. Allows for multiple selectors to be chained. The number of selected cuts for the previous becomes the number of maximum cuts for the following selector. We don't need to register the inner cut selectors with SCIP. """ struct ComposedCutSelector{ N, CS<:Union{ AbstractVector{<:AbstractCutSelector}, NTuple{N,AbstractCutSelector}, }, } <: AbstractCutSelector cutsels::CS end function ComposedCutSelector( cutsels::CS, ) where {N,CS<:NTuple{N,AbstractCutSelector}} return ComposedCutSelector{N,CS}(cutsels) end function ComposedCutSelector( cutsels::CS, ) where {CS<:AbstractVector{<:AbstractCutSelector}} return ComposedCutSelector{1,CS}(cutsels) end function select_cuts( cutsel::ComposedCutSelector, scip, cuts, forced_cuts, root, maxnslectedcuts, ) (retcode, nselectedcuts, result) = select_cuts( cutsel.cutsels[1], scip, cuts, forced_cuts, root, maxnslectedcuts, ) for idx in 2:length(cutsel.cutsels) if retcode != SCIP_OKAY || nselectedcuts == 0 return (retcode, nselectedcuts, result) end (retcode, nselectedcuts, result) = select_cuts( cutsel.cutsels[idx], scip, cuts, forced_cuts, root, nselectedcuts, ) end return (retcode, nselectedcuts, result) end """ Native SCIP cut selector, see SCIP source code for a description of the parameters and the underlying algorithm. See "Adaptive Cut Selection in Mixed-Integer Linear Programming" for a high-level overview. """ Base.@kwdef mutable struct HybridCutSelector <: AbstractCutSelector good_score_frac::Float64 = 0.9 bas_score_frac::Float64 = 0.0 max_parallelism::Float64 = 0.9 max_parallelism_root::Float64 = 0.9 weight_dircutoff_distance::Float64 = 0.0 weight_efficacy::Float64 = 1.0 weight_objective_parallelism::Float64 = 0.1 weight_int_support::Float64 = 0.1 end function select_cuts( cutsel::HybridCutSelector, scip, cuts, forced_cuts, root, maxnslectedcuts, ) nselected_cuts = Ref{Cint}(-1) maxparalellism = root ? cutsel.max_parallelism_root : cutsel.max_parallelism max_good_parallelism = max(maxparalellism, 0.5) retcode = LibSCIP.SCIPselectCutsHybrid( scip, cuts, forced_cuts, C_NULL, # random number generator cutsel.good_score_frac, cutsel.bas_score_frac, max_good_parallelism, maxparalellism, cutsel.weight_dircutoff_distance, cutsel.weight_efficacy, cutsel.weight_objective_parallelism, cutsel.weight_int_support, length(cuts), length(forced_cuts), maxnslectedcuts, nselected_cuts, ) # if SCIP_OKAY, should have nonnegative number of cuts @assert retcode != SCIP_OKAY || nselected_cuts[] >= 0 return (retcode, nselected_cuts[], SCIP_SUCCESS) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
3716
# heuristic interface # it is recommended to check https://scipopt.org/doc/html/HEUR.php for key concepts and interface """ Abstract class for Heuristic. A heuristic must implement `find_primal_solution`. It also stores all user data that must be available to run the heuristic. """ abstract type Heuristic end """ find_primal_solution( scip::Ptr{SCIP_}, heur::Heuristic, heurtiming::Heurtiming, nodeinfeasible::Bool, heur_ptr::Ptr{SCIP_HEUR}, ) -> (retcode, result) It must attempt to find primal solution(s). `retcode` indicates whether the selection went well. A typical result would be `SCIP_SUCCESS`, and retcode `SCIP_OKAY`. Use the methods `create_empty_scipsol` and `SCIPsetSolVal` to build solutions. Submit it to SCIP with `SCIPtrySolFree` """ function find_primal_solution(scip, heur, heurtiming, nodeinfeasible, heur_ptr) end function _find_primal_solution_callback( scip::Ptr{SCIP_}, heur_::Ptr{SCIP_HEUR}, heurtiming::SCIP_HEURTIMING, nodeinfeasible_::SCIP_Bool, result_::Ptr{SCIP_RESULT}, ) heurdata::Ptr{SCIP_HEURDATA} = SCIPheurGetData(heur_) heur = unsafe_pointer_to_objref(heurdata) nodeinfeasible = nodeinfeasible_ == SCIP.TRUE (retcode, result) = find_primal_solution( scip, heur, heurtiming, nodeinfeasible, heur_, )::Tuple{SCIP_RETCODE,SCIP_RESULT} if retcode != SCIP_OKAY return retcode end unsafe_store!(result_, result) return retcode end function _heurfree(::Ptr{SCIP_}, heur::Ptr{SCIP_HEUR}) # just like sepa, free the data on the SCIP side, # the Julia GC will take care of the objects SCIPheurSetData(heur, C_NULL) return SCIP_OKAY end """ Includes a heuristic plugin in SCIP and stores it in heuristic_storage. """ function include_heuristic( scip::Ptr{SCIP_}, heuristic::HT, heuristic_storage::Dict{Any,Ptr{SCIP_HEUR}}; name="", description="", dispchar='_', priority=10000, frequency=1, frequency_offset=0, maximum_depth=-1, timing_mask=SCIP_HEURTIMING_BEFORENODE, usessubscip=false, ) where {HT<:Heuristic} # ensure a unique name for the cut selector if name == "" name = "heuristic_$(string(HT))" end if dispchar == '_' dispchar = name[end] end heur__ = Ref{Ptr{SCIP_HEUR}}(C_NULL) if !ismutable(heuristic) throw( ArgumentError("The heuristic structure must be a mutable type"), ) end heurdata_ = pointer_from_objref(heuristic) heur_callback = @cfunction( _find_primal_solution_callback, SCIP_RETCODE, ( Ptr{SCIP_}, Ptr{SCIP_HEUR}, SCIP_HEURTIMING, SCIP_Bool, Ptr{SCIP_RESULT}, ), ) @SCIP_CALL SCIPincludeHeurBasic( scip, heur__, name, description, dispchar, priority, frequency, frequency_offset, maximum_depth, timing_mask, usessubscip, heur_callback, heurdata_, ) @assert heur__[] != C_NULL @SCIP_CALL SCIPsetHeurFree( scip, heur__[], @cfunction(_heurfree, SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_HEUR})), ) # store heuristic in storage (avoids GC-ing it) heuristic_storage[heuristic] = heur__[] end """ create_empty_scipsol(scip::Ptr{SCIP_}, heur_::Ptr{SCIP_HEUR}) -> Ptr{SCIP_SOL} Convenience wrapper to create an empty solution """ function create_empty_scipsol(scip::Ptr{SCIP_}, heur_::Ptr{SCIP_HEUR}) sol__ = Ref{Ptr{SCIP_SOL}}(C_NULL) @SCIP_CALL SCIPcreateSol(scip, sol__, heur_) return sol__[] end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
1053
import Libdl const depsjl_path = joinpath(@__DIR__, "..", "deps", "deps.jl") if isfile(depsjl_path) # User-provided SCIP library include(depsjl_path) else # Artifact from BinaryBuilder package import SCIP_PaPILO_jll if SCIP_PaPILO_jll.is_available() using SCIP_PaPILO_jll: libscip else using SCIP_jll: libscip end end function __init__() if VERSION >= v"1.9" config = LinearAlgebra.BLAS.lbt_get_config() if !any(lib -> lib.interface == :lp64, config.loaded_libs) LinearAlgebra.BLAS.lbt_forward(OpenBLAS32_jll.libopenblas_path) end end major = SCIPmajorVersion() minor = SCIPminorVersion() patch = SCIPtechVersion() current = VersionNumber("$major.$minor.$patch") required = VersionNumber("8") upperbound = VersionNumber("9") if current < required || current >= upperbound @error( "SCIP is installed at version $current, " * "supported are $required up to (excluding) $upperbound." ) end end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
10460
# Set of allowed Julia operators (as given by MOI) const OPS = [ :+, # n-ary :-, # unary, binary :*, # n-ary :/, # unary :^, # binary (or INTPOWER) :sqrt, # unary :exp, # unary :log, # unary :abs, # unary ] const UNARY_OPS_LOOKUP = ( exp=SCIPcreateExprExp, log=SCIPcreateExprLog, abs=SCIPcreateExprAbs, cos=SCIPcreateExprCos, sin=SCIPcreateExprSin, ) """ Extract operators from Julia expr recursively and convert to SCIP expressions. Returns the SCIP expression pointer, whether the expression is a pure value (without variables). """ function push_expr!( nonlin::NonlinExpr, scip::Ptr{SCIP_}, vars::Dict{VarRef,Ref{Ptr{SCIP_VAR}}}, expr::Expr, ) # Storage for SCIP_EXPR* expr__ = Ref{Ptr{SCIP_EXPR}}(C_NULL) num_children = length(expr.args) - 1 pure_value = false if Meta.isexpr(expr, :comparison) # range constraint # args: [lhs, <=, mid, <=, rhs], lhs and rhs constant @assert length(expr.args) == 5 @assert expr.args[2][1] == expr.args[4][1] == :<= # just call on middle expression, bounds are handled outside return push_expr!(nonlin, scip, vars, expr.args[3]) elseif Meta.isexpr(expr, :call) # operator op = expr.args[1] if op in (:(==), :<=, :>=) # args: [op, lhs, rhs], rhs constant @assert length(expr.args) == 3 # just call on lhs expression, bounds are handled outside return push_expr!(nonlin, scip, vars, expr.args[2]) elseif op == :^ # Special case: power with constant exponent. # The Julia expression considers the base and exponent to be # subexpressions. SCIP does in principle support constant # expressions, but in the case of SCIP_EXPR_REALPOWER, the exponent # value is stored directly, as the second child. @assert num_children == 2 # Base (first child) is proper sub-expression. base, pure_value = push_expr!(nonlin, scip, vars, expr.args[2]) # Exponent (second child) is stored as value. @assert isa(expr.args[3], Number) if !pure_value exponent = Cdouble(expr.args[3]) @SCIP_CALL SCIPcreateExprPow( scip, expr__, base[], exponent, C_NULL, C_NULL, ) end elseif op in (:-, :+) @assert num_children >= 1 if op === :- && num_children == 1 # Special case: unary version of minus. # Then, insert the actual subexpression: right, pure_value = push_expr!(nonlin, scip, vars, expr.args[2]) if !pure_value # Finally, add the (binary) minus: @SCIP_CALL SCIPcreateExprSum( scip, expr__, Cint(1), [right[]], [-1.0], 0.0, C_NULL, C_NULL, ) end else coef_mul = if op === :- -1.0 else 1.0 end subexprs_pairs = [ push_expr!(nonlin, scip, vars, expr.args[i+1]) for i in 1:num_children ] if all(pair -> pair[2], subexprs_pairs) pure_value = true else # replace pure-value expression by its evaluated value, since no expression has been evaluated yet subexprs = map(eachindex(subexprs_pairs)) do idx (subexpr, is_pure_value) = subexprs_pairs[idx] if is_pure_value expr_val = Meta.eval(expr.args[idx+1]) expr_ptr, _ = push_expr!(nonlin, scip, vars, expr_val) expr_ptr[] else subexpr[] end end coefs = fill(coef_mul, num_children) coefs[1] = 1.0 @SCIP_CALL SCIPcreateExprSum( scip, expr__, Cint(num_children), subexprs, coefs, 0.0, C_NULL, C_NULL, ) pure_value = false end end elseif op == :* @assert num_children >= 1 subexprs_pairs = [ push_expr!(nonlin, scip, vars, expr.args[i+1]) for i in 1:num_children ] if all(pair -> pair[2], subexprs_pairs) pure_value = true else subexprs = map(eachindex(subexprs_pairs)) do idx (subexpr, is_pure_value) = subexprs_pairs[idx] if is_pure_value expr_val = Meta.eval(expr.args[idx+1]) expr_ptr, _ = push_expr!(nonlin, scip, vars, expr_val) expr_ptr[] else subexpr[] end end @SCIP_CALL SCIPcreateExprProduct( scip, expr__, num_children, subexprs, 1.0, C_NULL, C_NULL, ) pure_value = false end elseif op in keys(UNARY_OPS_LOOKUP) # Unary operators @assert num_children == 1 # Insert child expression: child, pure_value = push_expr!(nonlin, scip, vars, expr.args[2]) if !pure_value @SCIP_CALL UNARY_OPS_LOOKUP[op]( scip, expr__, child[], C_NULL, C_NULL, ) end elseif op == :sqrt child, pure_value = push_expr!(nonlin, scip, vars, expr.args[2]) if !pure_value @SCIP_CALL SCIPcreateExprPow( scip, expr__, child[], 0.5, C_NULL, C_NULL, ) end elseif op == :/ @assert num_children == 2 # Transform L / R => L * R^-1.0 # Create left and right subexpression. left, pure_left = push_expr!(nonlin, scip, vars, expr.args[2]) inverse_right_expr = :($(expr.args[3])^-1.0) right, pure_right = push_expr!(nonlin, scip, vars, inverse_right_expr) if pure_left && pure_right pure_value = true else if pure_left && expr.args[2] isa Expr val = Meta.eval(expr.args[2]) left, _ = push_expr!(nonlin, scip, vars, val) end if pure_right val = Meta.eval(inverse_right_expr) right, _ = push_expr!(nonlin, scip, vars, val) end # TODO evaluate left or right @SCIP_CALL SCIPcreateExprProduct( scip, expr__, num_children, [left[], right[]], 1.0, C_NULL, C_NULL, ) end else # attempt computation of pure value try Meta.eval(expr) catch e error("Operator $op (in $expr) not supported by SCIP.jl!") end # if reaching this point, the expression is a pure value pure_value = true end elseif Meta.isexpr(expr, :ref) # variable # It should look like this: # :(x[MathOptInterface.VariableIndex(1)]) @assert expr.args[1] == :x @assert num_children == 1 vi = expr.args[2] # MOI.VariableIndex vr = VarRef(vi.value) v = vars[vr][] @SCIP_CALL SCIPcreateExprVar(scip, expr__, v, C_NULL, C_NULL) pure_value = false else error("Expression $expr not supported by SCIP.jl!") end if !pure_value # Return this expression to be referenced by parent expressions push!(nonlin.exprs, expr__) end return expr__, pure_value end function push_expr!( nonlin::NonlinExpr, scip::Ptr{SCIP_}, vars::Dict{VarRef,Ref{Ptr{SCIP_VAR}}}, expr::Number, ) # Storage for SCIP_EXPR* expr__ = Ref{Ptr{SCIP_EXPR}}(C_NULL) value = Cdouble(expr) @SCIP_CALL SCIPcreateExprValue(scip, expr__, value, C_NULL, C_NULL) @assert SCIPisExprValue(scip, expr__[]) == TRUE push!(nonlin.exprs, expr__) pure_value = true return expr__, pure_value end """ Add nonlinear constraint to problem, return cons ref. lhs ≤ expression ≤ rhs # Arguments - `expr::Expr`: Julia expression of nonlinear function, as given by MOI. - `lhs::Float64`: left-hand side for ranged constraint - `rhs::Float64`: right-hand side for ranged constraint """ function add_nonlinear_constraint( scipd::SCIPData, expr::Expr, lhs::Float64, rhs::Float64, ) nonlin = NonlinExpr() # convert expression recursively, extract root and variable pointers root_expr, pure_value = push_expr!(nonlin, scipd.scip[], scipd.vars, expr) if pure_value # TODO error("Constraint $expr with pure value") end # create and add cons_nonlinear cons__ = Ref{Ptr{SCIP_CONS}}(C_NULL) @SCIP_CALL SCIPcreateConsBasicNonlinear( scipd, cons__, "", root_expr[], lhs, rhs, ) @SCIP_CALL SCIPaddCons(scipd, cons__[]) # register and return cons ref push!(scipd.nonlinear_storage, nonlin) return store_cons!(scipd, cons__) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
11912
"Type-safe wrapper for `Int64`, references a variable." struct VarRef val::Int64 end "Type-safe wrapper for `Int64`, references a constraint." struct ConsRef val::Int64 end """ Subexpressions and variables referenced in an expression tree. Used to convert Julia expression to SCIP expression using recursive calls to the mutating push_expr!. """ mutable struct NonlinExpr exprs::Vector{Ref{Ptr{SCIP_EXPR}}} end NonlinExpr() = NonlinExpr([]) #to be moved to MOI_wrapper """ SCIPData holds pointers to SCIP data. It does not perform memory management and should not be created directly. """ mutable struct SCIPData scip::Ref{Ptr{SCIP_}} vars::Dict{VarRef,Ref{Ptr{SCIP_VAR}}} conss::Dict{ConsRef,Ref{Ptr{SCIP_CONS}}} var_count::Int64 cons_count::Int64 # Map from user-defined Julia types (keys are <: AbstractConstraintHandler # or <: AbstractConstraint, respectively) to the corresponding SCIP objects. # The reverse mapping is handled by SCIP itself. # This also serves to prevent premature GC. conshdlrs::Dict{Any,Ptr{SCIP_CONSHDLR}} conshdlrconss::Dict{Any,Ptr{SCIP_CONS}} # Map from user-defined types (keys are <: AbstractSeparator) to the # corresponding SCIP objects. sepas::Dict{Any,Ptr{SCIP_SEPA}} # User-defined cut selectors and branching rules cutsel_storage::Dict{Any,Ptr{SCIP_CUTSEL}} branchrule_storage::Dict{Any,Ptr{SCIP_BRANCHRULE}} heuristic_storage::Dict{Any,Ptr{SCIP_HEUR}} # to store expressions for release nonlinear_storage::Vector{NonlinExpr} end # Protect SCIPData from GC for ccall with Ptr{SCIP_} argument. Base.unsafe_convert(::Type{Ptr{SCIP_}}, scipd::SCIPData) = scipd.scip[] function free_scip(scipd::SCIPData) # Avoid double-free (SCIP will set the pointers to NULL). if scipd.scip[] != C_NULL for c in values(scipd.conss) @SCIP_CALL SCIPreleaseCons(scipd, c) end for nonlin in scipd.nonlinear_storage for expr in nonlin.exprs @SCIP_CALL SCIPreleaseExpr(scipd.scip[], expr) end end for v in values(scipd.vars) @SCIP_CALL SCIPreleaseVar(scipd, v) end @SCIP_CALL SCIPfree(scipd.scip) end @assert scipd.scip[] == C_NULL end "Set a parameter's current value." function get_parameter(scipd::SCIPData, name::AbstractString) param = SCIPgetParam(scipd, name) if param == C_NULL error("Unrecognized parameter: $name") end paramtype = SCIPparamGetType(param) if paramtype === SCIP_PARAMTYPE_BOOL value = Ref{SCIP_Bool}() @SCIP_CALL SCIPgetBoolParam(scipd, name, value) if value[] == TRUE return true elseif value[] == FALSE return false else error("encountered invalid value for a boolean: $(value[])") end elseif paramtype === SCIP_PARAMTYPE_INT value = Ref{Cint}() @SCIP_CALL SCIPgetIntParam(scipd, name, value) return value[] elseif paramtype === SCIP_PARAMTYPE_LONGINT value = Ref{Clonglong}() @SCIP_CALL SCIPgetLongintParam(scipd, name, value) return value[] elseif paramtype === SCIP_PARAMTYPE_REAL value = Ref{Cdouble}() @SCIP_CALL SCIPgetRealParam(scipd, name, value) return value[] elseif paramtype === SCIP_PARAMTYPE_CHAR value = Ref{Cchar}() @SCIP_CALL SCIPgetCharParam(scipd, name, value) return Char(value[]) elseif paramtype === SCIP_PARAMTYPE_STRING value = Ref{Ptr{Cchar}}() @SCIP_CALL SCIPgetStringParam(scipd, name, value) return unsafe_string(value[]) else error("Unexpected parameter type: $paramtype") end end "Set a parameter." function set_parameter(scipd::SCIPData, name::AbstractString, value) param = SCIPgetParam(scipd, name) if param == C_NULL error("Unrecognized parameter: $name") end paramtype = SCIPparamGetType(param) if paramtype === SCIP_PARAMTYPE_BOOL @SCIP_CALL SCIPsetBoolParam(scipd, name, value) elseif paramtype === SCIP_PARAMTYPE_INT @SCIP_CALL SCIPsetIntParam(scipd, name, value) elseif paramtype === SCIP_PARAMTYPE_LONGINT @SCIP_CALL SCIPsetLongintParam(scipd, name, value) elseif paramtype === SCIP_PARAMTYPE_REAL @SCIP_CALL SCIPsetRealParam(scipd, name, value) elseif paramtype === SCIP_PARAMTYPE_CHAR @SCIP_CALL SCIPsetCharParam(scipd, name, value) elseif paramtype === SCIP_PARAMTYPE_STRING @SCIP_CALL SCIPsetStringParam(scipd, name, value) else error("Unexpected parameter type: $paramtype") end return nothing end "Return pointer to SCIP variable." function var(scipd::SCIPData, vr::VarRef)::Ptr{SCIP_VAR} return scipd.vars[vr][] end "Return pointer to SCIP constraint." function cons(scipd::SCIPData, cr::ConsRef)::Ptr{SCIP_CONS} return scipd.conss[cr][] end "Store reference to variable, return VarRef" function store_var!(scipd::SCIPData, var__::Ref{Ptr{SCIP_VAR}}) scipd.var_count += 1 vr = VarRef(scipd.var_count) scipd.vars[vr] = var__ return vr end "Store reference to constraint, return ConsRef" function store_cons!(scipd::SCIPData, cons__::Ref{Ptr{SCIP_CONS}}) scipd.cons_count += 1 cr = ConsRef(scipd.cons_count) scipd.conss[cr] = cons__ return cr end "Add variable to problem (continuous, no bounds), return var ref." function add_variable(scipd::SCIPData) var__ = Ref{Ptr{SCIP_VAR}}(C_NULL) @SCIP_CALL SCIPcreateVarBasic( scipd, var__, "", -SCIPinfinity(scipd), SCIPinfinity(scipd), 0.0, SCIP_VARTYPE_CONTINUOUS, ) @SCIP_CALL SCIPaddVar(scipd, var__[]) return store_var!(scipd, var__) end "Delete variable from problem." function delete(scipd::SCIPData, vr::VarRef) # delete variable from SCIP problem deleted = Ref{SCIP_Bool}() @SCIP_CALL SCIPdelVar(scipd, var(scipd, vr), deleted) deleted[] == TRUE || error("Variable at $(vr.val) could not be deleted!") # release memory and remove reference @SCIP_CALL SCIPreleaseVar(scipd, scipd.vars[vr]) delete!(scipd.vars, vr) return nothing end "Delete constraint from problem." function delete(scipd::SCIPData, cr::ConsRef) @SCIP_CALL SCIPdelCons(scipd, cons(scipd, cr)) # release memory and remove reference @SCIP_CALL SCIPreleaseCons(scipd, scipd.conss[cr]) delete!(scipd.conss, cr) return nothing end """ Add (ranged) linear constraint to problem, return cons ref. # Arguments - `varrefs::AbstractArray{VarRef}`: variable references for affine terms. - `coefs::AbstractArray{Float64}`: coefficients for affine terms. - `lhs::Float64`: left-hand side for ranged constraint - `rhs::Float64`: right-hand side for ranged constraint Use `(-)SCIPinfinity(scip)` for one of the bounds if not applicable. """ function add_linear_constraint(scipd::SCIPData, varrefs, coefs, lhs, rhs) @assert length(varrefs) == length(coefs) vars = [var(scipd, vr) for vr in varrefs] cons__ = Ref{Ptr{SCIP_CONS}}(C_NULL) @SCIP_CALL SCIPcreateConsBasicLinear( scipd, cons__, "", length(vars), vars, coefs, lhs, rhs, ) @SCIP_CALL SCIPaddCons(scipd, cons__[]) return store_cons!(scipd, cons__) end """ Add (ranged) quadratic constraint to problem, return cons ref. # Arguments - `linrefs::AbstractArray{VarRef}`: variable references for affine terms. - `lincoefs::AbstractArray{Float64}`: coefficients for affine terms. - `quadrefs1::AbstractArray{VarRef}`: first variable references for quadratic terms. - `quadrefs2::AbstractArray{VarRef}`: second variable references for quadratic terms. - `quadcoefs::AbstractArray{Float64}`: coefficients for quadratic terms. - `lhs::Float64`: left-hand side for ranged constraint - `rhs::Float64`: right-hand side for ranged constraint Use `(-)SCIPinfinity(scip)` for one of the bounds if not applicable. """ function add_quadratic_constraint( scipd::SCIPData, linrefs, lincoefs, quadrefs1, quadrefs2, quadcoefs, lhs, rhs, ) @assert length(linrefs) == length(lincoefs) @assert length(quadrefs1) == length(quadrefs2) @assert length(quadrefs1) == length(quadcoefs) linvars = [var(scipd, vr) for vr in linrefs] quadvars1 = [var(scipd, vr) for vr in quadrefs1] quadvars2 = [var(scipd, vr) for vr in quadrefs2] cons__ = Ref{Ptr{SCIP_CONS}}(C_NULL) @SCIP_CALL SCIPcreateConsBasicQuadraticNonlinear( scipd, cons__, "", length(linvars), linvars, lincoefs, length(quadvars1), quadvars1, quadvars2, quadcoefs, lhs, rhs, ) @SCIP_CALL SCIPaddCons(scipd, cons__[]) return store_cons!(scipd, cons__) end """ Add special-ordered-set of type 1 to problem, return cons ref. # Arguments - `varrefs::AbstractArray{VarRef}`: variable references - `weights::AbstractArray{Float64}`: numeric weights """ function add_special_ordered_set_type1(scipd::SCIPData, varrefs, weights) @assert length(varrefs) == length(weights) vars = [var(scipd, vr) for vr in varrefs] cons__ = Ref{Ptr{SCIP_CONS}}(C_NULL) @SCIP_CALL SCIPcreateConsBasicSOS1( scipd, cons__, "", length(vars), vars, weights, ) @SCIP_CALL SCIPaddCons(scipd, cons__[]) return store_cons!(scipd, cons__) end """ Add special-ordered-set of type 2 to problem, return cons ref. # Arguments - `varrefs::AbstractArray{VarRef}`: variable references - `weights::AbstractArray{Float64}`: numeric weights """ function add_special_ordered_set_type2(scipd::SCIPData, varrefs, weights) @assert length(varrefs) == length(weights) vars = [var(scipd, vr) for vr in varrefs] cons__ = Ref{Ptr{SCIP_CONS}}(C_NULL) @SCIP_CALL SCIPcreateConsBasicSOS2( scipd, cons__, "", length(vars), vars, weights, ) @SCIP_CALL SCIPaddCons(scipd, cons__[]) return store_cons!(scipd, cons__) end """ Add indicator constraint to problem, return cons ref. y = 1 ==> a^T x ≤ rhs y has to be a binary variable, or SCIP will error. # Arguments - `y::VarRef`: reference for binary indicator variable - `x::Vector{VarRef}`: reference vector for variables - `a::Float64`: coefficients for x variable - `rhs::Float64`: right-hand side for linear constraint """ function add_indicator_constraint(scipd::SCIPData, y, x, a, rhs) SCIPvarIsBinary(var(scipd, y)) > 0 || error("indicator variable must be binary.") cons__ = Ref{Ptr{SCIP_CONS}}(C_NULL) xref = [var(scipd, x[i]) for i in eachindex(x)] @SCIP_CALL SCIPcreateConsBasicIndicator( scipd, cons__, "", var(scipd, y), length(x), xref, a, rhs, ) @SCIP_CALL SCIPaddCons(scipd, cons__[]) return store_cons!(scipd, cons__) end # Transform SCIP C function name as follows: # 1. Remove leading "SCIP" part (drop the first four characters). # 2. Convert camel case to snake case. # For example, `SCIPprintStatusStatistics` becomes `print_status_statistics`. const STATISTICS_FUNCS = map( x -> Symbol(camel_case_to_snake_case(string(x)[5:end])), SCIP_STATISTICS_FUNCS, ) for (scip_statistics_func, statistics_func) in zip(SCIP_STATISTICS_FUNCS, STATISTICS_FUNCS) @eval begin """ $($statistics_func)(scipd::SCIPData) Print statistics (calls `$($scip_statistics_func)`) to standard output. """ function $statistics_func end function $statistics_func(scipd::SCIPData) ret = $scip_statistics_func(scipd, C_NULL) ret !== nothing && @assert ret == SCIP_OKAY return nothing end end end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
6675
# # Wrapper for implementing SCIP separators in Julia. # # Please study the corresponding SCIP documentation first, to become familiar # with basic concepts and terms: https://www.scipopt.org/doc/html/SEPA.php # # The basic idea is that you create a new subtype of `AbstractSeparator` # to store the separator data and implement the fundamental callback by # adding a method to the function `exec_lp`. In `test/sepa.jl` and # `test/sepa_support.jl` you can find examples on how to use separators # # # Current limitations: # - We only support SEPAEXECLP, not SEPAEXECSOL. # - We don't support these optional methods: SEPAFREE, SEPACOPY, SEPAINIT, # SEPAINITSOL, SEPAEXITSOL # # # Abstract Supertypes: # """ AbstractSeparator Abstract supertype for objects that store all user data belonging to the separator. This object is also used for method dispatch with the callback functions. From SCIP's point-of-view, this objects corresponds to the SCIP_SEPADATA, but its memory is managed by Julia's GC. It's recommended to store a reference to your instance of `SCIPData` or `SCIP.Optimizer` here, so that you can use it within `exec_lp`. """ abstract type AbstractSeparator end # # Fundamental Callback for Julia. # """ exec_lp(separator::SEPA)::SCIP_RESULT Adds cutting planes to the model. Feasible solutions may be cutted off, as long as at least one optimal solution stays feasible. Use the functions `sol_values` to access the solution values. Acceptable result values are: * `SCIP_CUTOFF`: The current subproblem is infeasible. * `SCIP_CONSADDED`: Added a constraint. * `SCIP_REDUCEDDOM`: Reduced the domain of a variable. * `SCIP_SEPARATED`: Added a cutting plane. * `SCIP_DIDNOTFIND`: Searched for domain reductions or cutting planes, but did not find any. * `SCIP_DIDNOTRUN`: Separator was skipped. * `SCIP_DELAYED`: Separator was skipped, but should be called again. * `SCIP_NEWROUND`: A new separator round should be started without calling the remaining separator methods. """ function exec_lp end # # Fundamental callback functions with SCIP's C API. # # There is only a single, generic implementation for each of these, which are # passed to all user-defined SCIP separators, but they will call the user's # method in the function body. # """ Generic `exec_lp` function, matching the signature from SCIP's C API. """ function _sepaexeclp( scip::Ptr{SCIP_}, sepa::Ptr{SCIP_SEPA}, result::Ptr{SCIP_RESULT}, allowlocal::SCIP_Bool, ) # get Julia object out of separator data sepadata::Ptr{SCIP_SEPADATA} = SCIPsepaGetData(sepa) separator = unsafe_pointer_to_objref(sepadata) # call user method via dispatch res = exec_lp(separator) unsafe_store!(result, res) return SCIP_OKAY end """ Generic `free` function, matching the signature from SCIP's C API. """ function _sepafree(scip::Ptr{SCIP_}, sepa::Ptr{SCIP_SEPA}) # Here, we should free the separator data. But because this is an object # created and owned by Julia, we will let GC do it. # Instead, we will just set the pointer to NULL, so that SCIP will think # that it is taken care of. SCIPsepaSetData(sepa, C_NULL) return SCIP_OKAY end # # Adding a separator to SCIP. # """ include_sepa( scip::Ptr{SCIP_}, sepas::Dict{Any, Ptr{SCIP_SEPA}}, sepa::SEPA; name::String, description::String, priority::Int, freq::Int, maxbounddist::Float, usesubscip::Bool, delay::Bool ) Include a user defined separator `sepa` to the SCIP instance `scip`. """ function include_sepa( scip::Ptr{SCIP_}, sepas::Dict{Any,Ptr{SCIP_SEPA}}, sepa::SEPA; name="", description="", priority=0, freq=1, maxbounddist=0.0, usessubscip=false, delay=false, ) where {SEPA<:AbstractSeparator} # Get C function pointers from Julia functions _execlp = @cfunction( _sepaexeclp, SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_SEPA}, Ptr{SCIP_RESULT}, SCIP_Bool) ) _execsol = C_NULL # Store pointer to SCIP structure (for future C API calls) sepa__ = Ref{Ptr{SCIP_SEPA}}(C_NULL) # Hand over Julia object as separator data: sepadata_ = pointer_from_objref(sepa) # Try to create unique name, or else SCIP will complain! if name == "" name = "__sepa__$(length(sepas))" end # Register separator with SCIP instance. @SCIP_CALL SCIPincludeSepaBasic( scip, sepa__, name, description, priority, freq, maxbounddist, usessubscip, delay, _execlp, _execsol, sepadata_, ) # Sanity checks @assert sepa__[] != C_NULL # Set additional callbacks. @SCIP_CALL SCIPsetSepaFree( scip, sepa__[], @cfunction(_sepafree, SCIP_RETCODE, (Ptr{SCIP_}, Ptr{SCIP_SEPA})) ) # Register separator (for GC-protection and mapping). sepas[sepa] = sepa__[] end """ add_cut_sepa( scip::Ptr{SCIP_}, vars::Dict{VarRef, Ref{Ptr{SCIP_VAR}}} sepas::Dict{Any, Ptr{SCIP_SEPA}} sepa::SEPA, varrefs::AbstractArray{VarRef}, coefs::AbstractArray{Float64}, lhs::Float64, rhs::Float64, islocal::Bool, modifiable::Bool, removable::Bool ) Add the cut given by `varrefs`, `coefs`, `lhs` and `rhs` to `scip`. `add_cut_sepa` is intended to be called from the method `exec_lp`, that is associated to the separator `sepa`. # Arguments - islocal: is cut only valid locally? - modifiable: is row modifiable during node processing (subject to column generation)? - removable: should the row be removed from the LP due to aging or cleanup? """ function add_cut_sepa( scip::Ptr{SCIP_}, vars::Dict{VarRef,Ref{Ptr{SCIP_VAR}}}, sepas::Dict{Any,Ptr{SCIP_SEPA}}, sepa::SEPA, varrefs, coefs, lhs, rhs; islocal=false, modifiable=false, removable=true, ) where {SEPA<:AbstractSeparator} @assert length(varrefs) == length(coefs) vars = [vars[vr][] for vr in varrefs] row__ = Ref{Ptr{SCIP_ROW}}(C_NULL) sepa__ = sepas[sepa] @SCIP_CALL SCIPcreateEmptyRowSepa( scip, row__, sepa__, "", lhs, rhs, islocal, modifiable, removable, ) @SCIP_CALL SCIPaddVarsToRow(scip, row__[], length(vars), vars, coefs) if islocal infeasible = Ref{SCIP_Bool}() @SCIP_CALL SCIPaddRow(scip, row__[], true, infeasible) else @SCIP_CALL SCIPaddPoolCut(scip, row__[]) end @SCIP_CALL SCIPreleaseRow(scip, row__) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
552
function camel_case_to_snake_case(x::AbstractString) # from https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case s1 = replace(x, r"(.)([A-Z][a-z]+)" => s"\1_\2") return lowercase(replace(s1, r"([a-z0-9])([A-Z])" => s"\1_\2")) end """ SCIP_versionnumber() -> VersionNumber Current version of the SCIP binary """ function SCIP_versionnumber() major = SCIPmajorVersion() minor = SCIPminorVersion() patch = SCIPtechVersion() return VersionNumber(major, minor, patch) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
1218
include("LibSCIP.jl") using .LibSCIP const SCIP_ = LibSCIP.SCIP const TRUE = LibSCIP.TRUE const FALSE = LibSCIP.FALSE # SCIP_CALL: macro to check return codes macro SCIP_CALL(ex) quote v = $(esc(ex)) if v != SCIP_OKAY s = $(string(ex)) error("$s yielded SCIP code $v") end end end const SCIP_STATISTICS_FUNCS = [ :SCIPprintStatusStatistics, :SCIPprintTimingStatistics, :SCIPprintOrigProblemStatistics, :SCIPprintTransProblemStatistics, :SCIPprintPresolverStatistics, :SCIPprintConstraintStatistics, :SCIPprintConstraintTimingStatistics, :SCIPprintPropagatorStatistics, :SCIPprintConflictStatistics, :SCIPprintSeparatorStatistics, :SCIPprintPricerStatistics, :SCIPprintBranchruleStatistics, :SCIPprintHeuristicStatistics, :SCIPprintCompressionStatistics, :SCIPprintLPStatistics, :SCIPprintNLPStatistics, :SCIPprintRelaxatorStatistics, :SCIPprintTreeStatistics, :SCIPprintRootStatistics, :SCIPprintSolutionStatistics, :SCIPprintConcsolverStatistics, :SCIPprintBendersStatistics, :SCIPprintStatistics, :SCIPprintReoptStatistics, :SCIPprintBranchingStatistics, ]
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
3293
# # Adding constraint handlers, constraints, and cut selectors to SCIP.Optimizer. # """ include_conshdlr( o::Optimizer, ch::CH; name::String, description::String, enforce_priority::Int, check_priority::Int, eager_frequency::Int, needs_constraints::Bool ) Include a user defined constraint handler `ch` to SCIP optimizer instance `o`. All parameters have default values that can be set as keyword arguments. In particular, note the boolean `needs_constraints`: * If set to `true`, then the callbacks are only called for the constraints that were added explicitly using `add_constraint`. * If set to `false`, the callback functions will always be called, even if no corresponding constraint was added. It probably makes sense to set `misc/allowdualreds` to `FALSE` in this case. """ function include_conshdlr( o::Optimizer, ch::CH; name="", description="", enforce_priority=-15, check_priority=-7000000, eager_frequency=100, needs_constraints=true, ) where {CH<:AbstractConstraintHandler} include_conshdlr( o.inner.scip[], o.inner.conshdlrs, ch; name=name, description=description, enforce_priority=enforce_priority, check_priority=check_priority, eager_frequency=eager_frequency, needs_constraints=needs_constraints, ) end """ add_constraint( o::Optimizer, ch::CH, c::C; initial=true, separate=true, enforce=true, check=true, propagate=true, _local=false, modifiable=false, dynamic=false, removable=false, stickingatnode=false )::ConsRef Add constraint `c` belonging to user-defined constraint handler `ch` to model. Returns constraint reference. All keyword arguments are passed to the `SCIPcreateCons` call. """ function add_constraint( o::Optimizer, ch::CH, c::C; initial=true, separate=true, enforce=true, check=true, propagate=true, _local=false, modifiable=false, dynamic=false, removable=false, stickingatnode=false, ) where {CH<:AbstractConstraintHandler,C<:AbstractConstraint{CH}} return add_constraint( o.inner, ch, c; initial=initial, separate=separate, enforce=enforce, check=check, propagate=propagate, _local=_local, modifiable=modifiable, dynamic=dynamic, removable=removable, stickingatnode=stickingatnode, ) end function include_cutsel( o::Optimizer, cutsel::CS; name="", description="", priority=10000, ) where {CS<:AbstractCutSelector} return include_cutsel( o.inner.scip[], cutsel, o.inner.cutsel_storage; name=name, description=description, priority=priority, ) end function include_branchrule( o::Optimizer, branchrule::BR; name="", description="", priority=10000, ) where {BR<:AbstractBranchingRule} return include_branchrule( o.inner.scip[], branchrule, o.inner.branchrule_storage; name=name, description=description, priority=priority, ) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
1206
# generic constraints function MOI.get(o::Optimizer, ::MOI.ConstraintName, ci::CI)::String return GC.@preserve o unsafe_string(SCIPconsGetName(cons(o, ci))) end function MOI.set(o::Optimizer, ::MOI.ConstraintName, ci::CI, name::String) @SCIP_CALL SCIPchgConsName(o, cons(o, ci), name) return nothing end function MOI.set(o::Optimizer, ::MOI.ConstraintName, ci::CI{VI}, name::String) throw(MOI.VariableIndexConstraintNameError()) return nothing end function MOI.is_valid(o::Optimizer, c::CI{F,S}) where {F,S} cons_set = get(o.constypes, (F, S), nothing) if cons_set === nothing return false end if !in(ConsRef(c.value), cons_set) return false end return haskey(o.inner.conss, SCIP.ConsRef(c.value)) end function MOI.get(o::Optimizer, ::Type{MOI.ConstraintIndex}, name::String) ptr = SCIPfindCons(o, name) if ptr == C_NULL return nothing end cref = get(o.reference, ptr, nothing) if cref === nothing return cref end for ((F, S), setref) in o.constypes if cref in setref return CI{F,S}(cref.val) end end error("Constraint type not found for constraint $cref") end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
3076
function include_heuristic( o::Optimizer, heuristic::HT; name="", description="", dispchar='_', priority=10000, frequency=1, frequency_offset=0, maximum_depth=-1, timing_mask=SCIP_HEURTIMING_BEFORENODE, usessubscip=false, ) where {HT} return include_heuristic( o.inner.scip[], heuristic, o.inner.heuristic_storage; name=name, description=description, dispchar=dispchar, priority=priority, frequency=frequency, frequency_offset=frequency_offset, maximum_depth=maximum_depth, timing_mask=timing_mask, usessubscip=usessubscip, ) end mutable struct HeuristicCb <: Heuristic scipd::SCIPData heurcallback::Function end # If no cut callback is given, the cut callback does nothing. HeuristicCb(scipd::SCIPData) = HeuristicCb(scipd, cb_data -> nothing) """ Used for an argument to the heuristic callback, which in turn uses that argument to obtain the LP-solution via `MOI.get` and to add solutions via `MOI.submit`. """ mutable struct HeuristicCbData heur::HeuristicCb submit_called::Bool heurtiming::SCIP_HEURTIMING nodeinfeasible::Bool heur_ptr::Ptr{SCIP_HEUR} end function find_primal_solution(scip, heur::HeuristicCb, heurtiming, nodeinfeasible, heur_ptr) cb_data = HeuristicCbData(heur, false, heurtiming, nodeinfeasible, heur_ptr) heur.heurcallback(cb_data) result = cb_data.submit_called ? SCIP_FOUNDSOL : SCIP_DIDNOTFIND return SCIP_OKAY, result end # # MOI Interface for heuristic callbacks # function MOI.get(o::Optimizer, ::MOI.CallbackVariablePrimal{HeuristicCbData}, vs::Vector{VI}) return [SCIPgetSolVal(o, C_NULL, var(o, vi)) for vi in vs] end function MOI.set(o::Optimizer, ::MOI.HeuristicCallback, cb::Function) if o.moi_heuristic === nothing o.moi_heuristic = HeuristicCb(o.inner, cb) include_heuristic(o, o.moi_heuristic, name="MOI_heuristic", description="Heuristic set in the MOI optimizer") else o.moi_heuristic.cutcallback = cb end return nothing end MOI.supports(::Optimizer, ::MOI.HeuristicCallback) = true function MOI.submit( o::Optimizer, cb::MOI.HeuristicSolution{HeuristicCbData}, x::Vector{MOI.VariableIndex}, values::Vector{<:Real}, ) callback_data = cb.callback_data heuristic = callback_data.heur heur_ = o.inner.heuristic_storage[heuristic] sol = create_empty_scipsol(o.inner.scip[], heur_) for idx in eachindex(x) SCIP.@SCIP_CALL SCIP.SCIPsetSolVal( o.inner.scip[], sol, var(o, x[idx]), values[idx], ) end stored = Ref{SCIP_Bool}(SCIP.FALSE) @SCIP_CALL SCIPtrySolFree( o.inner.scip[], Ref(sol), SCIP.FALSE, SCIP.FALSE, SCIP.TRUE, SCIP.TRUE, SCIP.TRUE, stored, ) if stored[] == SCIP.TRUE callback_data.submit_called = true end end MOI.supports(::Optimizer, ::MOI.HeuristicSolution{HeuristicCbData}) = true
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
3199
# Indicator constraints function MOI.supports_constraint( ::Optimizer, ::Type{<:MOI.VectorAffineFunction}, ::Type{<:MOI.Indicator{MOI.ACTIVATE_ON_ONE,<:MOI.LessThan}}, ) true end function MOI.add_constraint( o::Optimizer, func::MOI.VectorAffineFunction{T}, set::MOI.Indicator{MOI.ACTIVATE_ON_ONE,LT}, ) where {T<:Real,LT<:MOI.LessThan} allow_modification(o) first_index_terms = [v.scalar_term for v in func.terms if v.output_index == 1] scalar_index_terms = [v.scalar_term for v in func.terms if v.output_index != 1] length(first_index_terms) == 1 || error( "There should be exactly one term in output_index 1, found $(length(first_index_terms))", ) y = VarRef(first_index_terms[1].variable.value) x = [VarRef(vi.variable.value) for vi in scalar_index_terms] a = [vi.coefficient for vi in scalar_index_terms] b = func.constants[2] # a^T x + b <= c ===> a^T <= c - b cr = add_indicator_constraint(o.inner, y, x, a, MOI.constant(set.set) - b) ci = CI{MOI.VectorAffineFunction{T},MOI.Indicator{MOI.ACTIVATE_ON_ONE,LT}}( cr.val, ) register!(o, ci) register!(o, cons(o, ci), cr) return ci end function MOI.get( o::Optimizer, ::MOI.ConstraintFunction, ci::CI{MOI.VectorAffineFunction{T},MOI.Indicator{MOI.ACTIVATE_ON_ONE,LT}}, ) where {T<:Real,LT<:MOI.LessThan} _throw_if_invalid(o, ci) indicator_cons = cons(o, ci)::Ptr{SCIP_CONS} bin_var = SCIPgetBinaryVarIndicator(indicator_cons)::Ptr{SCIP_VAR} slack_var = SCIPgetSlackVarIndicator(indicator_cons)::Ptr{SCIP_VAR} linear_cons = SCIPgetLinearConsIndicator(indicator_cons)::Ptr{SCIP_CONS} nvars::Int = SCIPgetNVarsLinear(o, linear_cons) vars = unsafe_wrap( Array{Ptr{SCIP_VAR}}, SCIPgetVarsLinear(o, linear_cons), nvars, ) orig_vars = get_original_variables(vars, nvars) vals = unsafe_wrap(Array{Float64}, SCIPgetValsLinear(o, linear_cons), nvars) aff_terms = [ AFF_TERM(vals[i], VI(ref(o, orig_vars[i]).val)) for i in 1:nvars if orig_vars[i] != slack_var ] ind_terms = [VEC_TERM(1, AFF_TERM(1.0, VI(ref(o, bin_var).val)))] vec_terms = [VEC_TERM(2, term) for term in aff_terms] return VAF(vcat(ind_terms, vec_terms), [0.0, 0.0]) end function MOI.get( o::Optimizer, ::MOI.ConstraintSet, ci::CI{MOI.VectorAffineFunction{T},MOI.Indicator{MOI.ACTIVATE_ON_ONE,LT}}, ) where {T<:Real,LT<:MOI.LessThan} _throw_if_invalid(o, ci) indicator_cons = cons(o, ci)::Ptr{SCIP_CONS} linear_cons = SCIPgetLinearConsIndicator(indicator_cons)::Ptr{SCIP_CONS} lhs = SCIPgetLhsLinear(o, linear_cons) rhs = SCIPgetRhsLinear(o, linear_cons) lhs == -SCIPinfinity(o) || error("Have lower bound on indicator constraint!") return MOI.Indicator{MOI.ACTIVATE_ON_ONE}(MOI.LessThan(rhs)) end function MOI.get( o::Optimizer, ::MOI.ListOfConstraintIndices{F,S}, ) where { F<:MOI.VectorAffineFunction{Float64}, S<:MOI.Indicator{MOI.ACTIVATE_ON_ONE,MOI.LessThan{Float64}}, } return [ MOI.ConstraintIndex{F,S}(consref.val) for consref in o.constypes[F, S] ] end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
2288
# linear constraints MOI.supports_constraint(o::Optimizer, ::Type{SAF}, ::Type{<:BOUNDS}) = true function MOI.add_constraint( o::Optimizer, func::F, set::S, ) where {F<:SAF,S<:BOUNDS} if func.constant != 0.0 throw(MOI.ScalarFunctionConstantNotZero{Float64,F,S}(func.constant)) end allow_modification(o) varrefs = [VarRef(t.variable.value) for t in func.terms] coefs = [t.coefficient for t in func.terms] lhs, rhs = bounds(set) lhs = lhs === nothing ? -SCIPinfinity(o) : lhs rhs = rhs === nothing ? SCIPinfinity(o) : rhs cr = add_linear_constraint(o.inner, varrefs, coefs, lhs, rhs) ci = CI{F,S}(cr.val) register!(o, ci) register!(o, cons(o, ci), cr) return ci end function MOI.set( o::SCIP.Optimizer, ::MOI.ConstraintSet, ci::CI{<:SAF,S}, set::S, ) where {S<:BOUNDS} allow_modification(o) lhs, rhs = bounds(set) lhs = lhs === nothing ? -SCIPinfinity(o) : lhs rhs = rhs === nothing ? SCIPinfinity(o) : rhs @SCIP_CALL SCIPchgLhsLinear(o, cons(o, ci), lhs) @SCIP_CALL SCIPchgRhsLinear(o, cons(o, ci), rhs) return nothing end function MOI.get( o::Optimizer, ::MOI.ConstraintFunction, ci::CI{<:SAF,S}, ) where {S<:BOUNDS} _throw_if_invalid(o, ci) c = cons(o, ci) nvars::Int = SCIPgetNVarsLinear(o, c) vars = unsafe_wrap(Array{Ptr{SCIP_VAR}}, SCIPgetVarsLinear(o, c), nvars) vals = unsafe_wrap(Array{Float64}, SCIPgetValsLinear(o, c), nvars) orig_vars = get_original_variables(vars, nvars) terms = [AFF_TERM(vals[i], VI(ref(o, orig_vars[i]).val)) for i in 1:nvars] # can not identify constant anymore (is merged with lhs,rhs) return SAF(terms, 0.0) end function MOI.get( o::Optimizer, ::MOI.ConstraintSet, ci::CI{<:SAF,S}, ) where {S<:BOUNDS} _throw_if_invalid(o, ci) lhs = SCIPgetLhsLinear(o, cons(o, ci)) rhs = SCIPgetRhsLinear(o, cons(o, ci)) return from_bounds(S, lhs, rhs) end function MOI.modify( o::Optimizer, ci::CI{<:SAF,<:BOUNDS}, change::MOI.ScalarCoefficientChange{Float64}, ) allow_modification(o) @SCIP_CALL SCIPchgCoefLinear( o, cons(o, ci), var(o, change.variable), change.new_coefficient, ) return nothing end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
907
# Nonlinear constraints (objective not supported) MOI.supports(::Optimizer, ::MOI.NLPBlock) = true function MOI.set(o::Optimizer, ::MOI.NLPBlock, data::MOI.NLPBlockData) # We don't actually store the data (to be queried later during the solve # process). Instead, we extract the expression graphs and add the # corresponding constraints to the model directly. if data.has_objective error("Nonlinear objective not supported by SCIP.jl!") end # go back to problem stage allow_modification(o::Optimizer) MOI.initialize(data.evaluator, [:ExprGraph]) for i in 1:length(data.constraint_bounds) expr = MOI.constraint_expr(data.evaluator, i) bounds = data.constraint_bounds[i] cr = add_nonlinear_constraint(o.inner, expr, bounds.lower, bounds.upper) # Not registering or returning constraint reference! end return nothing end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
2278
# Objective function & sense. # # SCIP only supports affine objectives. For quadratic or nonlinear objectives, # the solver will depend on bridges with auxiliary variables. Single variable # objectives are also accepted, but the type is not correctly remembered. MOI.supports(::Optimizer, ::MOI.ObjectiveSense) = true MOI.supports(::Optimizer, ::MOI.ObjectiveFunction{SAF}) = true function MOI.set(o::Optimizer, ::MOI.ObjectiveFunction{SAF}, obj::SAF) allow_modification(o) # reset objective coefficient of all variables first for v in values(o.inner.vars) @SCIP_CALL SCIPchgVarObj(o, v[], 0.0) end # set new objective coefficients, summing coefficients for t in obj.terms v = var(o, t.variable) oldcoef = SCIPvarGetObj(v) newcoef = oldcoef + t.coefficient @SCIP_CALL SCIPchgVarObj(o, v, newcoef) end @SCIP_CALL SCIPaddOrigObjoffset(o, obj.constant - SCIPgetOrigObjoffset(o)) o.objective_function_set = true return nothing end function MOI.get(o::Optimizer, ::MOI.ObjectiveFunction{SAF}) terms = AFF_TERM[] for vr in keys(o.inner.vars) vi = VI(vr.val) coef = SCIPvarGetObj(var(o, vi)) coef == 0.0 || push!(terms, AFF_TERM(coef, vi)) end constant = SCIPgetOrigObjoffset(o) return SAF(terms, constant) end function MOI.set( o::Optimizer, ::MOI.ObjectiveSense, sense::MOI.OptimizationSense, ) allow_modification(o) if sense == MOI.MIN_SENSE @SCIP_CALL SCIPsetObjsense(o, SCIP_OBJSENSE_MINIMIZE) elseif sense == MOI.MAX_SENSE @SCIP_CALL SCIPsetObjsense(o, SCIP_OBJSENSE_MAXIMIZE) else # erasing objective MOI.set(o, MOI.ObjectiveFunction{SAF}(), SAF([], 0.0)) end o.objective_sense = sense return nothing end function MOI.get(o::Optimizer, ::MOI.ObjectiveSense) return something(o.objective_sense, MOI.FEASIBILITY_SENSE) end function MOI.modify( o::Optimizer, ::MOI.ObjectiveFunction{SAF}, change::MOI.ScalarCoefficientChange{Float64}, ) allow_modification(o) @SCIP_CALL SCIPchgVarObj(o, var(o, change.variable), change.new_coefficient) o.objective_function_set = true return nothing end MOI.get(::Optimizer, ::MOI.ObjectiveFunctionType) = SAF
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
5627
# quadratic constraints MOI.supports_constraint(o::Optimizer, ::Type{SQF}, ::Type{<:BOUNDS}) = true function MOI.add_constraint(o::Optimizer, func::SQF, set::S) where {S<:BOUNDS} if func.constant != 0.0 error( "SCIP does not support quadratic constraints with a constant offset.", ) end allow_modification(o) # affine terms linrefs = [VarRef(t.variable.value) for t in func.affine_terms] lincoefs = [t.coefficient for t in func.affine_terms] # quadratic terms quadrefs1 = [VarRef(t.variable_1.value) for t in func.quadratic_terms] quadrefs2 = [VarRef(t.variable_2.value) for t in func.quadratic_terms] # Divide coefficients by 2 iff they come from the diagonal: # Take coef * x * y as-is, but turn coef * x^2 into coef/2 * x^2. factor = 1.0 .- 0.5 * (quadrefs1 .== quadrefs2) quadcoefs = factor .* [t.coefficient for t in func.quadratic_terms] # range lhs, rhs = bounds(set) lhs = lhs === nothing ? -SCIPinfinity(o) : lhs rhs = rhs === nothing ? SCIPinfinity(o) : rhs cr = add_quadratic_constraint( o.inner, linrefs, lincoefs, quadrefs1, quadrefs2, quadcoefs, lhs, rhs, ) ci = CI{SQF,S}(cr.val) register!(o, ci) register!(o, cons(o, ci), cr) return ci end function MOI.set( o::SCIP.Optimizer, ::MOI.ConstraintSet, ci::CI{SQF,S}, set::S, ) where {S<:BOUNDS} allow_modification(o) lhs, rhs = bounds(set) lhs = lhs === nothing ? -SCIPinfinity(o) : lhs rhs = rhs === nothing ? SCIPinfinity(o) : rhs @SCIP_CALL SCIPchgLhsQuadratic(o, cons(o, ci), lhs) @SCIP_CALL SCIPchgRhsQuadratic(o, cons(o, ci), rhs) return nothing end function MOI.get( o::Optimizer, ::MOI.ConstraintFunction, ci::CI{SQF,S}, ) where {S<:BOUNDS} _throw_if_invalid(o, ci) c = cons(o, ci) expr_ref = SCIPgetExprNonlinear(c) # This call is required to get quaddata computed in the expression isq = Ref{UInt32}(100) @SCIP_CALL LibSCIP.SCIPcheckExprQuadratic(o, expr_ref, isq) if isq[] != 1 error( "Constraint index $ci pointing to a non-quadratic expression $expr_ref", ) end constant_ref = Ref{Cdouble}(-1.0) n_linear_terms_ref = Ref{Cint}(-1) linear_exprs = Ref{Ptr{Ptr{LibSCIP.SCIP_EXPR}}}() lincoefs = Ref{Ptr{Cdouble}}() n_quad_terms_ref = Ref{Cint}(-1) n_bilinear_terms_ref = Ref{Cint}(-1) LibSCIP.SCIPexprGetQuadraticData( expr_ref, constant_ref, n_linear_terms_ref, linear_exprs, lincoefs, n_quad_terms_ref, n_bilinear_terms_ref, C_NULL, C_NULL, ) lin_expr_vec = unsafe_wrap(Vector{Ptr{Cvoid}}, linear_exprs[], n_linear_terms_ref[]) lin_coeff_vec = unsafe_wrap(Vector{Cdouble}, lincoefs[], n_linear_terms_ref[]) func = SCIP.SQF([], [], constant_ref[]) for idx in 1:n_linear_terms_ref[] var_ptr = LibSCIP.SCIPgetVarExprVar(lin_expr_vec[idx]) func += lin_coeff_vec[idx] * MOI.VariableIndex(o.reference[var_ptr].val) end for term_idx in 1:n_quad_terms_ref[] var_expr = Ref{Ptr{Cvoid}}() lin_coef_ref = Ref{Cdouble}() sqr_coef_ref = Ref{Cdouble}() LibSCIP.SCIPexprGetQuadraticQuadTerm( expr_ref, term_idx - 1, # 0-indexed terms var_expr, lin_coef_ref, sqr_coef_ref, C_NULL, C_NULL, C_NULL, ) @assert lin_coef_ref[] == 0.0 if sqr_coef_ref[] != 0.0 var_ptr = LibSCIP.SCIPgetVarExprVar(var_expr[]) var_idx = MOI.VariableIndex(o.reference[var_ptr].val) MOI.Utilities.operate!( +, Float64, func, sqr_coef_ref[] * var_idx * var_idx, ) end end for term_idx in 1:n_bilinear_terms_ref[] var_expr1 = Ref{Ptr{Cvoid}}() var_expr2 = Ref{Ptr{Cvoid}}() coef_ref = Ref{Cdouble}() LibSCIP.SCIPexprGetQuadraticBilinTerm( expr_ref, term_idx - 1, var_expr1, var_expr2, coef_ref, C_NULL, C_NULL, ) if coef_ref[] != 0.0 var_ptr1 = LibSCIP.SCIPgetVarExprVar(var_expr1[]) var_idx1 = MOI.VariableIndex(o.reference[var_ptr1].val) var_ptr2 = LibSCIP.SCIPgetVarExprVar(var_expr2[]) var_idx2 = MOI.VariableIndex(o.reference[var_ptr2].val) MOI.Utilities.operate!( +, Float64, func, coef_ref[] * var_idx1 * var_idx2, ) end end return func end function MOI.get( o::Optimizer, ::MOI.ConstraintSet, ci::CI{SQF,S}, ) where {S<:BOUNDS} _throw_if_invalid(o, ci) c = cons(o, ci) lhs = SCIPgetLhsNonlinear(c) rhs = SCIPgetRhsNonlinear(c) return from_bounds(S, lhs, rhs) end function MOI.get( o::Optimizer, ::MOI.ConstraintPrimal, ci::CI{SQF,S}, ) where {S<:BOUNDS} _throw_if_invalid(o, ci) c = cons(o, ci) expr_ref = SCIPgetExprNonlinear(c) isq = Ref{UInt32}(100) @SCIP_CALL LibSCIP.SCIPcheckExprQuadratic(o, expr_ref, isq) if isq[] != 1 error( "Constraint index $ci pointing to a non-quadratic expression $expr_ref", ) end sol = SCIPgetBestSol(o) @SCIP_CALL SCIPevalExpr(o, expr_ref, sol, Clonglong(0)) return SCIPexprGetEvalValue(expr_ref) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
4302
# results term_status_map = Dict( SCIP_STATUS_UNKNOWN => MOI.OPTIMIZE_NOT_CALLED, SCIP_STATUS_USERINTERRUPT => MOI.INTERRUPTED, SCIP_STATUS_NODELIMIT => MOI.NODE_LIMIT, SCIP_STATUS_TOTALNODELIMIT => MOI.NODE_LIMIT, SCIP_STATUS_STALLNODELIMIT => MOI.OTHER_LIMIT, SCIP_STATUS_TIMELIMIT => MOI.TIME_LIMIT, SCIP_STATUS_MEMLIMIT => MOI.MEMORY_LIMIT, SCIP_STATUS_GAPLIMIT => MOI.OPTIMAL, SCIP_STATUS_SOLLIMIT => MOI.SOLUTION_LIMIT, SCIP_STATUS_BESTSOLLIMIT => MOI.OTHER_LIMIT, SCIP_STATUS_RESTARTLIMIT => MOI.OTHER_LIMIT, SCIP_STATUS_OPTIMAL => MOI.OPTIMAL, SCIP_STATUS_INFEASIBLE => MOI.INFEASIBLE, SCIP_STATUS_UNBOUNDED => MOI.DUAL_INFEASIBLE, SCIP_STATUS_INFORUNBD => MOI.INFEASIBLE_OR_UNBOUNDED, SCIP_STATUS_TERMINATE => MOI.INTERRUPTED, ) function MOI.get(o::Optimizer, ::MOI.TerminationStatus) return term_status_map[SCIPgetStatus(o)] end function MOI.get(o::Optimizer, attr::MOI.PrimalStatus) return if 1 <= attr.result_index <= MOI.get(o, MOI.ResultCount()) MOI.FEASIBLE_POINT else MOI.NO_SOLUTION end end function MOI.get(::Optimizer, ::MOI.DualStatus) return MOI.NO_SOLUTION end function MOI.get(o::Optimizer, ::MOI.ResultCount)::Int status = SCIPgetStatus(o) if status in [SCIP_STATUS_UNBOUNDED, SCIP_STATUS_INFORUNBD] return 0 end return SCIPgetNSols(o) end function MOI.get(o::Optimizer, ::MOI.RawStatusString) return string(SCIPgetStatus(o)) end "Make sure that SCIP is currently in one of the allowed stages." function assert_stage(o::Optimizer, stages) stage = SCIPgetStage(o) if !(stage in stages) error("SCIP is wrong stage ($stage, need $stages)!") end end "Make sure that the problem was solved (SCIP is in SOLVED stage)." function assert_solved(o::Optimizer) # SCIP's stage is SOLVING when stopped by user limit! assert_stage( o, ( SCIP_STAGE_PRESOLVING, SCIP_STAGE_SOLVING, SCIP_STAGE_PRESOLVED, SCIP_STAGE_SOLVED, ), ) # Check for invalid status (when stage is SOLVING). status = SCIPgetStatus(o) if status in (SCIP_STATUS_UNKNOWN, SCIP_STATUS_USERINTERRUPT, SCIP_STATUS_TERMINATE) error("SCIP's solving was interrupted, but not by a user-given limit!") end end "Make sure that: TRANSFORMED ≤ stage ≤ SOLVED." assert_after_prob(o::Optimizer) = assert_stage(o, SCIP_Stage.(3:10)) function MOI.get(o::Optimizer, attr::MOI.ObjectiveValue) assert_solved(o) MOI.check_result_index_bounds(o, attr) sols = unsafe_wrap(Array{Ptr{SCIP_SOL}}, SCIPgetSols(o), SCIPgetNSols(o)) return SCIPgetSolOrigObj(o, sols[attr.result_index]) end function MOI.get(o::Optimizer, attr::MOI.VariablePrimal, vi::VI) assert_solved(o) MOI.check_result_index_bounds(o, attr) sols = unsafe_wrap(Array{Ptr{SCIP_SOL}}, SCIPgetSols(o), SCIPgetNSols(o)) return SCIPgetSolVal(o, sols[attr.result_index], var(o, vi)) end function MOI.get(o::Optimizer, attr::MOI.ConstraintPrimal, ci::CI{VI,<:BOUNDS}) assert_solved(o) MOI.check_result_index_bounds(o, attr) sols = unsafe_wrap(Array{Ptr{SCIP_SOL}}, SCIPgetSols(o), SCIPgetNSols(o)) return SCIPgetSolVal(o, sols[attr.result_index], var(o, VI(ci.value))) end function MOI.get( o::Optimizer, attr::MOI.ConstraintPrimal, ci::CI{<:SAF,<:BOUNDS}, ) assert_solved(o) MOI.check_result_index_bounds(o, attr) sols = unsafe_wrap(Array{Ptr{SCIP_SOL}}, SCIPgetSols(o), SCIPgetNSols(o)) return SCIPgetActivityLinear(o, cons(o, ci), sols[attr.result_index]) end function MOI.get(o::Optimizer, ::MOI.ObjectiveBound) assert_after_prob(o) return SCIPgetDualbound(o) end function MOI.get(o::Optimizer, ::MOI.RelativeGap) assert_stage( o, [SCIP_STAGE_PRESOLVING, SCIP_STAGE_SOLVING, SCIP_STAGE_SOLVED], ) return SCIPgetGap(o) end function MOI.get(o::Optimizer, ::MOI.SolveTimeSec) return SCIPgetSolvingTime(o) end function MOI.get(o::Optimizer, ::MOI.SimplexIterations) assert_stage( o, [SCIP_STAGE_PRESOLVING, SCIP_STAGE_SOLVING, SCIP_STAGE_SOLVED], ) return SCIPgetNLPIterations(o) end function MOI.get(o::Optimizer, ::MOI.NodeCount) return SCIPgetNNodes(o) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
2803
# # Adding separators to SCIP.Optimizer. # """ include_sepa( o::Optimizer, sepa::SEPA; name::String, description::String, priority::Int, freq::Int, maxbounddist::Float, usesubscip::Bool, delay::Bool ) Include a user defined separator `sepa` to the SCIP optimizer instance `o`. All parameters have default values, that can be set as keyword arguments. """ function include_sepa( o::Optimizer, sepa::SEPA; name="", description="", priority=0, freq=1, maxbounddist=0.0, usessubscip=false, delay=false, ) where {SEPA<:AbstractSeparator} include_sepa( o.inner.scip[], o.inner.sepas, sepa; name=name, description=description, priority=priority, freq=freq, maxbounddist=maxbounddist, usessubscip=usessubscip, delay=delay, ) end # # Separator for cutcallbacks. # mutable struct CutCbSeparator <: AbstractSeparator scipd::SCIPData cutcallback::Function end # If no cut callback is given, the cut callback does nothing. CutCbSeparator(scipd::SCIPData) = CutCbSeparator(scipd, cb_data -> nothing) """ Used for an argument to the cut callback, which in turn uses that argument to obtain the LP-solution via `MOI.get` and to add cuts via `MOI.submit`. """ mutable struct CutCbData sepa::CutCbSeparator "Did the cut callback call submit?" submit_called::Bool end function exec_lp(sepa::CutCbSeparator) cb_data = CutCbData(sepa, false) sepa.cutcallback(cb_data) return cb_data.submit_called ? SCIP_SEPARATED : SCIP_DIDNOTFIND end # # MOI Interface for cutcallbacks # function MOI.get(o::Optimizer, ::MOI.CallbackVariablePrimal{CutCbData}, vi) return SCIPgetSolVal(o, C_NULL, var(o, vi)) end function MOI.set(o::Optimizer, ::MOI.UserCutCallback, cb::Function) if o.moi_separator === nothing o.moi_separator = CutCbSeparator(o.inner, cb) include_sepa(o, o.moi_separator) else o.moi_separator.cutcallback = cb end end MOI.supports(::Optimizer, ::MOI.UserCutCallback) = true function MOI.submit( o::Optimizer, cb_data::MOI.UserCut{CutCbData}, func::SAF, set::S, ) where {S<:BOUNDS} varrefs = [VarRef(t.variable.value) for t in func.terms] coefs = [t.coefficient for t in func.terms] lhs, rhs = bounds(set) lhs = lhs === nothing ? -SCIPinfinity(o) : lhs rhs = rhs === nothing ? SCIPinfinity(o) : rhs add_cut_sepa( o.inner.scip[], o.inner.vars, o.inner.sepas, cb_data.callback_data.sepa, varrefs, coefs, lhs, rhs, ) cb_data.callback_data.submit_called = true end MOI.supports(::Optimizer, ::MOI.UserCut{CutCbData}) = true
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
2003
# Special-Ordered-Set type 1 MOI.supports_constraint(o::Optimizer, ::Type{VECTOR}, ::Type{SOS1}) = true function MOI.add_constraint(o::Optimizer, func::VECTOR, set::SOS1) allow_modification(o) varrefs = [VarRef(vi.value) for vi in func.variables] cr = add_special_ordered_set_type1(o.inner, varrefs, set.weights) ci = CI{VECTOR,SOS1}(cr.val) register!(o, ci) register!(o, cons(o, ci), cr) return ci end function MOI.get(o::Optimizer, ::MOI.ConstraintFunction, ci::CI{VECTOR,SOS1}) _throw_if_invalid(o, ci) c = cons(o, ci) nvars::Int = SCIPgetNVarsSOS1(o, c) vars = unsafe_wrap(Array{Ptr{SCIP_VAR}}, SCIPgetVarsSOS1(o, c), nvars) return VECTOR([VI(ref(o, v).val) for v in vars]) end function MOI.get(o::Optimizer, ::MOI.ConstraintSet, ci::CI{VECTOR,SOS1}) _throw_if_invalid(o, ci) c = cons(o, ci) nvars::Int = SCIPgetNVarsSOS1(o, c) weights = unsafe_wrap(Array{Float64}, SCIPgetWeightsSOS1(o, c), nvars) return SOS1(weights) end # Special-Ordered-Set type 2 MOI.supports_constraint(o::Optimizer, ::Type{VECTOR}, ::Type{SOS2}) = true function MOI.add_constraint(o::Optimizer, func::VECTOR, set::SOS2) allow_modification(o) varrefs = [VarRef(vi.value) for vi in func.variables] cr = add_special_ordered_set_type2(o.inner, varrefs, set.weights) ci = CI{VECTOR,SOS2}(cr.val) register!(o, ci) register!(o, cons(o, ci), cr) return ci end function MOI.get(o::Optimizer, ::MOI.ConstraintFunction, ci::CI{VECTOR,SOS2}) _throw_if_invalid(o, ci) c = cons(o, ci) nvars::Int = SCIPgetNVarsSOS2(o, c) vars = unsafe_wrap(Array{Ptr{SCIP_VAR}}, SCIPgetVarsSOS2(o, c), nvars) return VECTOR([VI(ref(o, v).val) for v in vars]) end function MOI.get(o::Optimizer, ::MOI.ConstraintSet, ci::CI{VECTOR,SOS2}) _throw_if_invalid(o, ci) c = cons(o, ci) nvars::Int = SCIPgetNVarsSOS2(o, c) weights = unsafe_wrap(Array{Float64}, SCIPgetWeightsSOS2(o, c), nvars) return SOS2(weights) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
11589
## variables (general) function MOI.add_variable(o::Optimizer) allow_modification(o) vr = add_variable(o.inner) var::Ptr{SCIP_VAR} = o.inner.vars[vr][] register!(o, var, vr) return MOI.VariableIndex(vr.val) end MOI.add_variables(o::Optimizer, n) = [MOI.add_variable(o) for i in 1:n] MOI.get(o::Optimizer, ::MOI.NumberOfVariables) = length(o.inner.vars) function MOI.get(o::Optimizer, ::MOI.ListOfVariableIndices) sort!([VI(k.val) for k in keys(o.inner.vars)]; by=v -> v.value) end MOI.is_valid(o::Optimizer, vi::VI) = haskey(o.inner.vars, VarRef(vi.value)) function MOI.get(o::Optimizer, ::MOI.VariableName, vi::VI)::String return GC.@preserve o unsafe_string(SCIPvarGetName(var(o, vi))) end function MOI.set(o::Optimizer, ::MOI.VariableName, vi::VI, name::String) @SCIP_CALL SCIPchgVarName(o, var(o, vi), name) return nothing end MOI.supports(::Optimizer, ::MOI.VariableName, ::Type{MOI.VariableIndex}) = true function MOI.get(o::Optimizer, ::Type{MOI.VariableIndex}, name::String) ptr = SCIPfindVar(o, name) if ptr == C_NULL return nothing end var_ref = get(o.reference, ptr, nothing) if var_ref === nothing return var_ref end return MOI.VariableIndex(var_ref.val) end function MOI.delete(o::Optimizer, vi::VI) # Note: SCIP does not currently support deletion of variables that are still # present in some constraint. We don't want the overhead of keeping track of # the variable-in-constraint relation, so, to be conservative, we only allow # to delete a variable when there are no constraints in the model. if length(o.inner.conss) > 0 throw( MOI.DeleteNotAllowed( vi, "Can not delete variable while model contains constraints!", ), ) end allow_modification(o) if !haskey(o.inner.vars, VarRef(vi.value)) throw(MOI.InvalidIndex(vi)) end # TODO still necessary? if !haskey(o.reference, var(o, vi)) throw(MOI.InvalidIndex(vi)) end haskey(o.binbounds, vi) && delete!(o.binbounds, vi) delete!(o.reference, var(o, vi)) delete(o.inner, VarRef(vi.value)) return nothing end ## variable types (binary, integer) MOI.supports_constraint(o::Optimizer, ::Type{VI}, ::Type{<:VAR_TYPES}) = true scip_vartype(::Type{MOI.ZeroOne}) = SCIP_VARTYPE_BINARY scip_vartype(::Type{MOI.Integer}) = SCIP_VARTYPE_INTEGER function MOI.add_constraint(o::Optimizer, vi::VI, set::S) where {S<:VAR_TYPES} allow_modification(o) v = var(o, vi) infeasible = Ref{SCIP_Bool}() @SCIP_CALL SCIPchgVarType(o, v, scip_vartype(S), infeasible) # TODO: warn if infeasible[] == TRUE? if S <: MOI.ZeroOne # Need to adjust bounds for SCIP, which fails with an error otherwise. # Check for conflicts with existing bounds first: lb, ub = SCIPvarGetLbOriginal(v), SCIPvarGetUbOriginal(v) if lb == -SCIPinfinity(o) && ub == SCIPinfinity(o) @debug "Implicitly setting bounds [0,1] for binary variable at $(vi.value)!" @SCIP_CALL SCIPchgVarLb(o, v, 0.0) @SCIP_CALL SCIPchgVarUb(o, v, 1.0) else # Store old bounds for later recovery. o.binbounds[vi] = MOI.Interval(lb, ub) if ub > 1.0 @debug "Tightening upper bound $ub to 1 for binary variable at $(vi.value)!" @SCIP_CALL SCIPchgVarUb(o, v, 1.0) end if lb < 0.0 @debug "Tightening lower bound $lb to 0 for binary variable at $(vi.value)!" @SCIP_CALL SCIPchgVarLb(o, v, 0.0) end end end # use var index for cons index of this type i = vi.value return register!(o, CI{VI,S}(i)) end function MOI.delete(o::Optimizer, ci::CI{VI,S}) where {S<:VAR_TYPES} _throw_if_invalid(o, ci) allow_modification(o) vi = VI(ci.value) v = var(o, vi) # Reset bounds from constraint if this was a binary, see below. reset_bounds = SCIPvarGetType(v) == SCIP_VARTYPE_BINARY # don't actually delete any SCIP constraint, just reset type infeasible = Ref{SCIP_Bool}() @SCIP_CALL SCIPchgVarType( o, var(o, vi), SCIP_VARTYPE_CONTINUOUS, infeasible, ) # TODO: warn if infeasible[] == TRUE? # Can only change bounds after changing the var type. if reset_bounds bounds = get(o.binbounds, vi, nothing) if bounds !== nothing @SCIP_CALL SCIPchgVarLb(o, v, bounds.lower) @SCIP_CALL SCIPchgVarUb(o, v, bounds.upper) end end # but do delete the constraint reference delete!(o.constypes[VI, S], ConsRef(ci.value)) return nothing end ## variable bounds MOI.supports_constraint(o::Optimizer, ::Type{VI}, ::Type{<:BOUNDS}) = true function MOI.add_constraint(o::Optimizer, vi::VI, set::S) where {S<:BOUNDS} allow_modification(o) v = var(o, vi) inf = SCIPinfinity(o) newlb, newub = bounds(set) newlb = newlb === nothing ? -inf : newlb newub = newub === nothing ? inf : newub # Check for existing bounds first. oldlb, oldub = SCIPvarGetLbOriginal(v), SCIPvarGetUbOriginal(v) if (oldlb != -inf && newlb != -inf || oldub != inf && newub != inf) # special case: implicit bounds for binaries if SCIPvarGetType(v) == SCIP_VARTYPE_BINARY # Store new bounds o.binbounds[vi] = MOI.Interval(newlb, newub) if newlb < 0.0 @debug "Ignoring relaxed lower bound $newlb for binary variable at $(vi.value)!" newlb = oldlb end if newub > 1.0 @debug "Ignoring relaxed upper bounds $newub for binary variable at $(vi.value)!" newub = oldub end if newlb != oldlb || newub != oldub @debug "Overwriting existing bounds [0.0,1.0] with [$newlb,$newub] for binary variable at $(vi.value)!" end else # general case (non-binary variable) # TODO find initially-set bound constraint throw(MOI.LowerBoundAlreadySet{S,S}(vi)) end end if newlb != -inf @SCIP_CALL SCIPchgVarLb(o, v, newlb) end if newub != inf @SCIP_CALL SCIPchgVarUb(o, v, newub) end # use var index for cons index of this type i = vi.value return register!(o, CI{VI,S}(i)) end function reset_bounds( o::Optimizer, v, lb, ub, ci::CI{VI,S}, ) where {S<:Union{MOI.Interval{Float64},MOI.EqualTo{Float64}}} @SCIP_CALL SCIPchgVarLb(o, v, lb) @SCIP_CALL SCIPchgVarUb(o, v, ub) end function reset_bounds( o::Optimizer, v, lb, ub, ci::CI{VI,MOI.GreaterThan{Float64}}, ) @SCIP_CALL SCIPchgVarLb(o, v, lb) end function reset_bounds(o::Optimizer, v, lb, ub, ci::CI{VI,MOI.LessThan{Float64}}) @SCIP_CALL SCIPchgVarUb(o, v, ub) end function MOI.delete(o::Optimizer, ci::CI{VI,S}) where {S<:BOUNDS} _throw_if_invalid(o, ci) allow_modification(o) # Don't actually delete any SCIP constraint, just reset bounds vi = VI(ci.value) v = var(o, vi) if SCIPvarGetType(v) == SCIP_VARTYPE_BINARY reset_bounds(o, v, 0.0, 1.0, ci) else inf = SCIPinfinity(o) reset_bounds(o, v, -inf, inf, ci) end # but do delete the constraint reference haskey(o.binbounds, vi) && delete!(o.binbounds, vi) delete!(o.constypes[VI, S], ConsRef(ci.value)) return nothing end function MOI.set( o::Optimizer, ::MOI.ConstraintSet, ci::CI{VI,S}, set::S, ) where {S<:BOUNDS} allow_modification(o) v = var(o, VI(ci.value)) # cons index is actually var index lb, ub = bounds(set) old_interval = get(o.binbounds, VI(ci.value), MOI.Interval(0.0, 1.0)) if lb !== nothing if SCIPvarGetType(v) == SCIP_VARTYPE_BINARY lb = max(lb, 0.0) end @SCIP_CALL SCIPchgVarLb(o, v, lb) o.binbounds[VI(ci.value)] = MOI.Interval(lb, old_interval.upper) end if ub !== nothing if SCIPvarGetType(v) == SCIP_VARTYPE_BINARY ub = min(ub, 1.0) end @SCIP_CALL SCIPchgVarUb(o, v, ub) o.binbounds[VI(ci.value)] = MOI.Interval(old_interval.lower, ub) end return nothing end # TODO: is actually wrong for unbounded variables? function MOI.is_valid(o::Optimizer, ci::CI{VI,S}) where {S<:BOUNDS} if !haskey(o.inner.vars, VarRef(ci.value)) return false end cons_set = get(o.constypes, (VI, S), nothing) if cons_set === nothing return false end return ConsRef(ci.value) in o.constypes[VI, S] end function MOI.get( o::Optimizer, ::MOI.ConstraintFunction, ci::CI{VI,S}, ) where {S<:BOUNDS} if !MOI.is_valid(o, ci) throw(MOI.InvalidIndex(ci)) end return VI(ci.value) end function MOI.get( o::Optimizer, ::MOI.ConstraintSet, ci::CI{VI,S}, ) where {S<:BOUNDS} if !MOI.is_valid(o, ci) throw(MOI.InvalidIndex(ci)) end vi = VI(ci.value) v = var(o, vi) lb, ub = SCIPvarGetLbOriginal(v), SCIPvarGetUbOriginal(v) if SCIPvarGetType(v) == SCIP_VARTYPE_BINARY bounds = o.binbounds[vi] lb, ub = bounds.lower, bounds.upper end return from_bounds(S, lb, ub) end function MOI.is_valid( o::Optimizer, ci::CI{VI,S}, ) where {S<:Union{MOI.ZeroOne,MOI.Integer}} if !haskey(o.inner.vars, VarRef(ci.value)) return false end return ConsRef(ci.value) in o.constypes[VI, S] end function MOI.get(o::Optimizer, ::MOI.ConstraintSet, ci::CI{VI,MOI.ZeroOne}) vi = VI(ci.value) v = var(o, vi) if SCIPvarGetType(v) == SCIP_VARTYPE_BINARY return MOI.ZeroOne() end throw(MOI.InvalidIndex(ci)) end function MOI.get(o::Optimizer, ::MOI.ConstraintSet, ci::CI{VI,MOI.Integer}) vi = VI(ci.value) v = var(o, vi) if SCIPvarGetType(v) == SCIP_VARTYPE_INTEGER return MOI.Integer() end throw(MOI.InvalidIndex(ci)) end function MOI.get(o::Optimizer, ::MOI.ConstraintFunction, ci::CI{VI,MOI.ZeroOne}) vi = VI(ci.value) v = var(o, vi) if SCIPvarGetType(v) == SCIP_VARTYPE_BINARY return vi end throw(MOI.InvalidIndex(ci)) end function MOI.get(o::Optimizer, ::MOI.ConstraintFunction, ci::CI{VI,MOI.Integer}) vi = VI(ci.value) v = var(o, vi) if SCIPvarGetType(v) == SCIP_VARTYPE_INTEGER return vi end throw(MOI.InvalidIndex(ci)) end # (partial) warm starts MOI.supports(::Optimizer, ::MOI.VariablePrimalStart, ::Type{VI}) = true function MOI.get(o::Optimizer, ::MOI.VariablePrimalStart, vi::VI) return if haskey(o.start, vi) o.start[vi] else nothing end end function MOI.set( o::Optimizer, ::MOI.VariablePrimalStart, vi::VI, value::Float64, ) o.start[vi] = value return end function MOI.set( o::Optimizer, ::MOI.VariablePrimalStart, vi::VI, value::Nothing, ) if haskey(o.start, vi) delete!(o.start, vi) end return end function MOI.set(::Optimizer, ::MOI.ConstraintFunction, ::CI{VI}, ::VI) throw(MOI.SettingVariableIndexNotAllowed()) end function get_original_variables(vars::Array{Ptr{SCIP_VAR}}, nvars::Int) scalar = Ref(1.0) constant = Ref(0.0) orig_vars = map(1:nvars) do i var = Ref(vars[i]) @SCIP_CALL SCIPvarGetOrigvarSum(var, scalar, constant) @assert scalar[] == 1.0 @assert constant[] == 0.0 var[] end return orig_vars end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
18360
using MathOptInterface const MOI = MathOptInterface const MOIB = MOI.Bridges const MOIT = MOI.Test const VI = MOI.VariableIndex const CI = MOI.ConstraintIndex function var_bounds(o::SCIP.Optimizer, vi::VI) return MOI.get( o, MOI.ConstraintSet(), CI{VI,MOI.Interval{Float64}}(vi.value), ) end function chg_bounds(o::SCIP.Optimizer, vi::VI, set::S) where {S} ci = CI{VI,S}(vi.value) MOI.set(o, MOI.ConstraintSet(), ci, set) return nothing end @testset "SOS1" begin optimizer = SCIP.Optimizer(; display_verblevel=0) x, y, z = MOI.add_variables(optimizer, 3) MOI.add_constraint(optimizer, x, MOI.LessThan(1.0)) MOI.add_constraint(optimizer, y, MOI.LessThan(1.0)) MOI.add_constraint(optimizer, z, MOI.LessThan(1.0)) c = MOI.add_constraint( optimizer, MOI.VectorOfVariables([x, y, z]), MOI.SOS1([1.0, 2.0, 3.0]), ) MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 2.0, 3.0], [x, y, z]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) @test MOI.get(optimizer, MOI.ConstraintFunction(), c) == MOI.VectorOfVariables([x, y, z]) @test MOI.get(optimizer, MOI.ConstraintSet(), c) == MOI.SOS1([1.0, 2.0, 3.0]) MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT atol, rtol = 1e-6, 1e-6 @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 3.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), z) ≈ 1.0 atol = atol rtol = rtol end @testset "SOS2" begin optimizer = SCIP.Optimizer(; display_verblevel=0) x, y, z = MOI.add_variables(optimizer, 3) MOI.add_constraint(optimizer, x, MOI.LessThan(1.0)) MOI.add_constraint(optimizer, y, MOI.LessThan(1.0)) MOI.add_constraint(optimizer, z, MOI.LessThan(1.0)) c = MOI.add_constraint( optimizer, MOI.VectorOfVariables([x, y, z]), MOI.SOS2([1.0, 2.0, 3.0]), ) MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 2.0, 3.0], [x, y, z]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) @test MOI.get(optimizer, MOI.ConstraintFunction(), c) == MOI.VectorOfVariables([x, y, z]) @test MOI.get(optimizer, MOI.ConstraintSet(), c) == MOI.SOS2([1.0, 2.0, 3.0]) MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT atol, rtol = 1e-6, 1e-6 @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 5.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), z) ≈ 1.0 atol = atol rtol = rtol end @testset "indicator constraints" begin optimizer = SCIP.Optimizer() x1 = MOI.add_variable(optimizer) x2 = MOI.add_variable(optimizer) x3 = MOI.add_variable(optimizer) y = MOI.add_variable(optimizer) t = MOI.add_constraint(optimizer, y, MOI.ZeroOne()) iset = MOI.Indicator{MOI.ACTIVATE_ON_ONE}(MOI.LessThan(1.0)) ind_func = MOI.VectorAffineFunction( [ MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, y)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x1)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x2)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x3)), ], [0.0, 0.0], ) c = MOI.add_constraint(optimizer, ind_func, iset) @test MOI.get(optimizer, MOI.ConstraintFunction(), c) ≈ ind_func @test MOI.get(optimizer, MOI.ConstraintSet(), c) == iset @test MOI.delete(optimizer, c) === nothing # adding incorrect function throws ind_func_wrong = MOI.VectorAffineFunction( [ MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, y)), MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, x1)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x2)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x3)), ], [0.0, 0.0], ) @test_throws ErrorException MOI.add_constraint( optimizer, ind_func_wrong, iset, ) ind_func_wrong2 = MOI.VectorAffineFunction( [ MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x2)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x3)), ], [0.0, 0.0], ) @test_throws ErrorException MOI.add_constraint( optimizer, ind_func_wrong2, iset, ) end @testset "deleting variables" begin optimizer = SCIP.Optimizer() # add variable and constraint x = MOI.add_variable(optimizer) c = MOI.add_constraint( optimizer, MOI.ScalarAffineFunction([MOI.ScalarAffineTerm(1.0, x)], 0.0), MOI.EqualTo(0.0), ) @test !MOI.is_empty(optimizer) # delete them (constraint first!) MOI.delete(optimizer, c) MOI.delete(optimizer, x) @test MOI.is_empty(optimizer) # add variable and constraint (again) x = MOI.add_variable(optimizer) c = MOI.add_constraint( optimizer, MOI.ScalarAffineFunction([MOI.ScalarAffineTerm(1.0, x)], 0.0), MOI.EqualTo(0.0), ) @test !MOI.is_empty(optimizer) # fail to delete them in wrong order @test_throws MOI.DeleteNotAllowed MOI.delete(optimizer, x) end @testset "set_parameter" begin # bool optimizer = SCIP.Optimizer(; branching_preferbinary=true) @test MOI.get( optimizer, MOI.RawOptimizerAttribute("branching/preferbinary"), ) == true # int optimizer = SCIP.Optimizer(; conflict_minmaxvars=1) @test MOI.get( optimizer, MOI.RawOptimizerAttribute("conflict/minmaxvars"), ) == 1 # long int optimizer = SCIP.Optimizer(; heuristics_alns_maxnodes=2) @test MOI.get( optimizer, MOI.RawOptimizerAttribute("heuristics/alns/maxnodes"), ) == 2 # real optimizer = SCIP.Optimizer(; branching_scorefac=0.15) @test MOI.get(optimizer, MOI.RawOptimizerAttribute("branching/scorefac")) == 0.15 # char optimizer = SCIP.Optimizer(; branching_scorefunc='s') @test MOI.get( optimizer, MOI.RawOptimizerAttribute("branching/scorefunc"), ) == 's' # string optimizer = SCIP.Optimizer(; heuristics_alns_rewardfilename="abc.txt") @test MOI.get( optimizer, MOI.RawOptimizerAttribute("heuristics/alns/rewardfilename"), ) == "abc.txt" # invalid @test_throws ErrorException SCIP.Optimizer(some_invalid_param_name=true) end @testset "use RawParameter" begin optimizer = SCIP.Optimizer() # bool MOI.set( optimizer, MOI.RawOptimizerAttribute("branching/preferbinary"), true, ) @test MOI.get( optimizer, MOI.RawOptimizerAttribute("branching/preferbinary"), ) == true # int MOI.set(optimizer, MOI.RawOptimizerAttribute("conflict/minmaxvars"), 1) @test MOI.get( optimizer, MOI.RawOptimizerAttribute("conflict/minmaxvars"), ) == 1 # long int MOI.set(optimizer, MOI.RawOptimizerAttribute("heuristics/alns/maxnodes"), 2) @test MOI.get( optimizer, MOI.RawOptimizerAttribute("heuristics/alns/maxnodes"), ) == 2 # real MOI.set(optimizer, MOI.RawOptimizerAttribute("branching/scorefac"), 0.15) @test MOI.get(optimizer, MOI.RawOptimizerAttribute("branching/scorefac")) == 0.15 # char MOI.set(optimizer, MOI.RawOptimizerAttribute("branching/scorefunc"), 's') @test MOI.get( optimizer, MOI.RawOptimizerAttribute("branching/scorefunc"), ) == 's' # string MOI.set( optimizer, MOI.RawOptimizerAttribute("heuristics/alns/rewardfilename"), "abc.txt", ) @test MOI.get( optimizer, MOI.RawOptimizerAttribute("heuristics/alns/rewardfilename"), ) == "abc.txt" # invalid @test_throws ErrorException MOI.set( optimizer, MOI.RawOptimizerAttribute("some/invalid/param/name"), true, ) end @testset "Silent" begin optimizer = SCIP.Optimizer() @test MOI.supports(optimizer, MOI.Silent()) # "loud" by default @test MOI.get(optimizer, MOI.Silent()) == false @test MOI.get(optimizer, MOI.RawOptimizerAttribute("display/verblevel")) == 4 # make it silent MOI.set(optimizer, MOI.Silent(), true) @test MOI.get(optimizer, MOI.Silent()) == true @test MOI.get(optimizer, MOI.RawOptimizerAttribute("display/verblevel")) == 0 # but a user can override it MOI.set(optimizer, MOI.RawOptimizerAttribute("display/verblevel"), 1) @test MOI.get(optimizer, MOI.Silent()) == false @test MOI.get(optimizer, MOI.RawOptimizerAttribute("display/verblevel")) == 1 end @testset "Query results (before/after solve)" begin optimizer = SCIP.Optimizer(; display_verblevel=0) atol, rtol = 1e-6, 1e-6 x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.GreaterThan(0.0)) MOI.add_constraint(optimizer, y, MOI.GreaterThan(0.0)) c = MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.0), ) MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 2.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # before optimize: can not query most results @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.NO_SOLUTION @test_throws ErrorException MOI.get(optimizer, MOI.ObjectiveValue()) @test_throws ErrorException MOI.get(optimizer, MOI.VariablePrimal(), x) @test_throws ErrorException MOI.get(optimizer, MOI.ConstraintPrimal(), c) @test_throws ErrorException MOI.get(optimizer, MOI.ObjectiveBound()) @test_throws ErrorException MOI.get(optimizer, MOI.RelativeGap()) @test MOI.get(optimizer, MOI.SolveTimeSec()) ≈ 0.0 atol = atol rtol = rtol @test_throws ErrorException MOI.get(optimizer, MOI.SimplexIterations()) @test MOI.get(optimizer, MOI.NodeCount()) == 0 # after optimize MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 2.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.ConstraintPrimal(), c) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.ObjectiveBound()) ≈ 2.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.RelativeGap()) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.SolveTimeSec()) < 1.0 @test MOI.get(optimizer, MOI.SimplexIterations()) <= 3 # conservative @test MOI.get(optimizer, MOI.NodeCount()) <= 1 # conservative end @testset "Primal start values" begin # stop after first feasible solution optimizer = SCIP.Optimizer(; display_verblevel=0, limits_solutions=1, presolving_maxrounds=0, ) atol, rtol = 1e-6, 1e-6 # x, y binary x, y = MOI.add_variables(optimizer, 2) b1 = MOI.add_constraint(optimizer, x, MOI.ZeroOne()) b2 = MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # x + y <= 1 c = MOI.add_constraint(optimizer, 1.0x + y, MOI.LessThan(1.0)) # max x + 2y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), 1.0x + 2.0y, ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # optimal solution: x = 0, y = 1, value = 2 # we submit the suboptimal x = 1 as start value @test MOI.supports(optimizer, MOI.VariablePrimalStart(), MOI.VariableIndex) # first set only the value for one variable MOI.set(optimizer, MOI.VariablePrimalStart(), x, 1.0) @test MOI.get(optimizer, MOI.VariablePrimalStart(), x) == 1.0 @test MOI.get(optimizer, MOI.VariablePrimalStart(), y) === nothing # unset the value MOI.set(optimizer, MOI.VariablePrimalStart(), x, nothing) @test MOI.get(optimizer, MOI.VariablePrimalStart(), x) === nothing @test MOI.get(optimizer, MOI.VariablePrimalStart(), y) === nothing # set all values (again) MOI.set(optimizer, MOI.VariablePrimalStart(), [x, y], [1.0, nothing]) @test MOI.get(optimizer, MOI.VariablePrimalStart(), x) == 1.0 @test MOI.get(optimizer, MOI.VariablePrimalStart(), y) === nothing # "solve" MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.SOLUTION_LIMIT @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT end @testset "No dual solution" begin optimizer = SCIP.Optimizer(; display_verblevel=0) MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.DualStatus()) == MOI.NO_SOLUTION end @testset "broken indicator test" for presolving in (1, 0) model = MOIB.full_bridge_optimizer( SCIP.Optimizer(; display_verblevel=0, presolving_maxrounds=presolving), Float64, ) config = MOIT.Config(; atol=5e-3, rtol=1e-4, exclude=Any[ MOI.ConstraintDual, MOI.ConstraintName, MOI.DualObjectiveValue, MOI.VariableBasisStatus, MOI.ConstraintBasisStatus, ], ) T = Float64 x1 = MOI.add_variable(model) x2 = MOI.add_variable(model) z1 = MOI.add_variable(model) z2 = MOI.add_variable(model) vc1 = MOI.add_constraint(model, z1, MOI.ZeroOne()) @test vc1.value == z1.value vc2 = MOI.add_constraint(model, z2, MOI.ZeroOne()) @test vc2.value == z2.value f1 = MOI.VectorAffineFunction( [ MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(T(1), z1)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(T(1), x2)), ], T[0, 0], ) iset1 = MOI.Indicator{MOI.ACTIVATE_ON_ZERO}(MOI.LessThan(T(8))) MOI.add_constraint(model, f1, iset1) f2 = MOI.VectorAffineFunction( [ MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(T(1), z2)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(T(1 // 5), x1)), MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(T(1), x2)), ], T[0, 0], ) iset2 = MOI.Indicator{MOI.ACTIVATE_ON_ONE}(MOI.LessThan(T(9))) MOI.add_constraint(model, f2, iset2) # Additional regular constraint. MOI.add_constraint( model, MOI.ScalarAffineFunction( [MOI.ScalarAffineTerm(T(1), x1), MOI.ScalarAffineTerm(T(1), x2)], T(0), ), MOI.LessThan(T(10)), ) # Disjunction (1-z1) ⋁ z2 MOI.add_constraint( model, MOI.ScalarAffineFunction( [MOI.ScalarAffineTerm(T(-1), z1), MOI.ScalarAffineTerm(T(1), z2)], T(0), ), MOI.GreaterThan(T(0)), ) MOI.set( model, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{T}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.(T[2, 3], [x1, x2]), T(0), ), ) MOI.set(model, MOI.ObjectiveSense(), MOI.MAX_SENSE) @test MOI.get(model, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED MOI.optimize!(model) if presolving == 1 && v"8.0.1" <= SCIP.SCIP_versionnumber() <= v"8.0.2" @test_broken MOI.get(model, MOI.TerminationStatus()) == config.optimal_status @test_broken MOI.get(model, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT else @test MOI.get(model, MOI.TerminationStatus()) == config.optimal_status @test MOI.get(model, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test ≈(MOI.get(model, MOI.ObjectiveValue()), T(115 // 4), config) @test ≈(MOI.get(model, MOI.VariablePrimal(), x1), T(5 // 4), config) @test ≈(MOI.get(model, MOI.VariablePrimal(), x2), T(35 // 4), config) @test ≈(MOI.get(model, MOI.VariablePrimal(), z1), T(1), config) @test ≈(MOI.get(model, MOI.VariablePrimal(), z2), T(1), config) end end @testset "Presolving $presolving" for presolving in (true, false) optimizer = SCIP.Optimizer(; display_verblevel=0) atol, rtol = 1e-6, 1e-6 x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.GreaterThan(0.0)) MOI.add_constraint(optimizer, y, MOI.GreaterThan(0.0)) c = MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.0), ) MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 2.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) @test MOI.get(optimizer, SCIP.Presolving()) == true MOI.set(optimizer, SCIP.Presolving(), presolving) @test MOI.get(optimizer, SCIP.Presolving()) == presolving # after optimize MOI.optimize!(optimizer) MOI.set(optimizer, SCIP.Presolving(), presolving) @test MOI.get(optimizer, SCIP.Presolving()) == presolving end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
8447
using MathOptInterface const MOI = MathOptInterface @testset "NaiveAllDiff (two binary vars)" begin optimizer = SCIP.Optimizer(; display_verblevel=0) atol, rtol = 1e-6, 1e-6 # add two binary variables: x, y x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # maximize 2x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([2.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add constraint handler with constraint all-diff(x, y) alldiffch = NaiveAllDiff.NADCH(optimizer) SCIP.include_conshdlr(optimizer, alldiffch; needs_constraints=true) alldiffcons = NaiveAllDiff.NADCons([x, y]) cr = SCIP.add_constraint(optimizer, alldiffch, alldiffcons) # solve problem and query result MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 2.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 0.0 atol = atol rtol = rtol end @testset "NaiveAllDiff (3 bin.vars, 2 pairwise conss)" begin optimizer = SCIP.Optimizer(; display_verblevel=0) atol, rtol = 1e-6, 1e-6 # add three binary variables x, y, z = MOI.add_variables(optimizer, 3) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) MOI.add_constraint(optimizer, z, MOI.ZeroOne()) # maximize 2x + 3y + 2z MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([2.0, 3.0, 2.0], [x, y, z]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add constraint handler with constraints all-diff(x, y), all-diff(y, x) alldiffch = NaiveAllDiff.NADCH(optimizer) SCIP.include_conshdlr(optimizer, alldiffch; needs_constraints=true) SCIP.add_constraint(optimizer, alldiffch, NaiveAllDiff.NADCons([x, y])) SCIP.add_constraint(optimizer, alldiffch, NaiveAllDiff.NADCons([y, z])) # solve problem and query result MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 4.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), z) ≈ 1.0 atol = atol rtol = rtol end @testset "NaiveAllDiff (3 bin.vars, 3 pairwise conss)" begin optimizer = SCIP.Optimizer(; display_verblevel=0) atol, rtol = 1e-6, 1e-6 # add three binary variables x, y, z = MOI.add_variables(optimizer, 3) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) MOI.add_constraint(optimizer, z, MOI.ZeroOne()) # maximize 2x + 3y + 2z MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([2.0, 3.0, 2.0], [x, y, z]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add constraint handler with constraints all-diff(x, y, z) alldiffch = NaiveAllDiff.NADCH(optimizer) SCIP.include_conshdlr(optimizer, alldiffch; needs_constraints=true) SCIP.add_constraint(optimizer, alldiffch, NaiveAllDiff.NADCons([x, y])) SCIP.add_constraint(optimizer, alldiffch, NaiveAllDiff.NADCons([x, z])) SCIP.add_constraint(optimizer, alldiffch, NaiveAllDiff.NADCons([y, z])) # solve problem and query result MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.INFEASIBLE @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.NO_SOLUTION @test MOI.get(optimizer, MOI.NodeCount()) >= 8 # complete enumeration end @testset "NaiveAllDiff (3 bin.vars, 1 cons with all)" begin optimizer = SCIP.Optimizer(; display_verblevel=0) atol, rtol = 1e-6, 1e-6 # add three binary variables x, y, z = MOI.add_variables(optimizer, 3) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) MOI.add_constraint(optimizer, z, MOI.ZeroOne()) # maximize 2x + 3y + 2z MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([2.0, 3.0, 2.0], [x, y, z]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add constraint handler with constraints all-diff(x, y, z) alldiffch = NaiveAllDiff.NADCH(optimizer) SCIP.include_conshdlr(optimizer, alldiffch; needs_constraints=true) SCIP.add_constraint(optimizer, alldiffch, NaiveAllDiff.NADCons([x, y, z])) # solve problem and query result MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.INFEASIBLE @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.NO_SOLUTION @test MOI.get(optimizer, MOI.NodeCount()) >= 8 # complete enumeration end @testset "NaiveAllDiff (3 int.vars, 1 cons with all)" begin optimizer = SCIP.Optimizer(; display_verblevel=0) atol, rtol = 1e-6, 1e-6 # add three integer variables, in {0, 1, 2} x, y, z = MOI.add_variables(optimizer, 3) for v in [x, y, z] MOI.add_constraint(optimizer, v, MOI.Integer()) MOI.add_constraint(optimizer, v, MOI.Interval(0.0, 2.0)) end # maximize 2x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([2.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add constraint handler with constraints all-diff(x, y, z) alldiffch = NaiveAllDiff.NADCH(optimizer) SCIP.include_conshdlr(optimizer, alldiffch; needs_constraints=true) SCIP.add_constraint(optimizer, alldiffch, NaiveAllDiff.NADCons([x, y, z])) # solve problem and query result MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 5.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 2.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), z) ≈ 0.0 atol = atol rtol = rtol end @testset "NoGoodCounter (2 binary vars)" begin optimizer = SCIP.Optimizer(; display_verblevel=0, presolving_maxrounds=0) allow_dual_reductions = MOI.RawOptimizerAttribute("misc/allowstrongdualreds") MOI.set(optimizer, allow_dual_reductions, SCIP.FALSE) atol, rtol = 1e-6, 1e-6 # add binary variables x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # maximize 2x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([2.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add constraint handler with constraints counter = NoGoodCounter.Counter(optimizer, [x, y]) SCIP.include_conshdlr(optimizer, counter; needs_constraints=false) # solve problem and query result MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.INFEASIBLE @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.NO_SOLUTION @test length(counter.solutions) == 4 end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
5160
using MathOptInterface const MOI = MathOptInterface # Simple evaluator for testing struct ExprEvaluator <: MOI.AbstractNLPEvaluator constraints::Vector{Expr} end function MOI.initialize(d::ExprEvaluator, requested_features::Vector{Symbol}) if requested_features != [:ExprGraph] error("Only supports expression graph!") end end MOI.constraint_expr(evaluator::ExprEvaluator, i) = evaluator.constraints[i] @testset "linear expressions" begin optimizer = SCIP.Optimizer(; display_verblevel=0) @test MOI.supports(optimizer, MOI.NLPBlock()) == true # min. -x # s.t. 2x + y <= 1.5 # x,y >= 0 x, y = MOI.add_variables(optimizer, 2) # bounds MOI.add_constraint(optimizer, x, MOI.GreaterThan(0.0)) MOI.add_constraint(optimizer, y, MOI.GreaterThan(0.0)) # "nonlinear" constraints (x => x[1], y => x[2]) data = MOI.NLPBlockData( [MOI.NLPBoundsPair(-Inf, 1.5)], ExprEvaluator([:(2 * x[$x] + x[$y] <= 1.5)]), false, # no objective ) MOI.set(optimizer, MOI.NLPBlock(), data) # objective MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.([-1.0], [x]), 0.0), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MIN_SENSE) # solve MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT atol, rtol = 1e-6, 1e-6 @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ -0.75 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 0.75 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 0.0 atol = atol rtol = rtol end @testset "pot pourri" begin optimizer = SCIP.Optimizer(; display_verblevel=0) @test MOI.supports(optimizer, MOI.NLPBlock()) == true num_vars = 21 x = MOI.add_variables(optimizer, num_vars) for i in 1:num_vars MOI.add_constraint(optimizer, x[i], MOI.Interval(0.1, 10.0)) end # Nonlinear equations. rhs = 2.0 expressions = Expr[ :(x[$(x[1])] + 0.5 == rhs), # VARIDX / CONSTANT :(x[$(x[2])] - x[$(x[3])] == rhs), # MINUS (binary) :(-x[$(x[4])] + 4.0 == rhs), # MINUS (unary) :(x[$(x[5])] + x[$(x[6])] + x[$(x[7])] == rhs), # SUM :(x[$(x[8])] * x[$(x[9])] * x[$(x[10])] == rhs), # PRODUCT :((x[$(x[11])])^3 == rhs), # INTPOWER :((x[$(x[12])])^0.8 == rhs), # REALPOWER :(x[$(x[13])] / x[$(x[14])] == rhs), # DIV :(sqrt(x[$(x[15])]) == rhs), # SQRT :(exp(x[$(x[16])]) == rhs), # EXP :(log(x[$(x[17])]) == rhs), # LOG :(abs(x[$(x[18])] - 11) == rhs), # ABS :(cos(x[$(x[19])]) + 1 == rhs), # COS :(sin(x[$(x[20])]) + 2 == rhs), # SIN :(x[$(x[21])] + tan(rand()) / (1 + 1.2^4.2) - 2 * 1 / 4 == rhs), # additional terms ] data = MOI.NLPBlockData( [MOI.NLPBoundsPair(rhs, rhs) for i in 1:length(expressions)], ExprEvaluator(expressions), false, # no objective ) MOI.set(optimizer, MOI.NLPBlock(), data) # Solve and get results. MOI.optimize!(optimizer) @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT sol = MOI.get(optimizer, MOI.VariablePrimal(), x) # Evaluate lhs of all the expressions with solution values. atol, rtol = 1e-6, 1e-6 @test sol[1] + 0.5 ≈ rhs atol = atol rtol = rtol @test sol[2] - sol[3] ≈ rhs atol = atol rtol = rtol @test -sol[4] + 4.0 ≈ rhs atol = atol rtol = rtol @test sol[5] + sol[6] + sol[7] ≈ rhs atol = atol rtol = rtol @test sol[8] * sol[9] * sol[10] ≈ rhs atol = atol rtol = rtol @test (sol[11])^3 ≈ rhs atol = atol rtol = rtol @test (sol[12])^0.8 ≈ rhs atol = atol rtol = rtol @test sol[13] / sol[14] ≈ rhs atol = atol rtol = rtol @test sqrt(sol[15]) ≈ rhs atol = atol rtol = rtol @test exp(sol[16]) ≈ rhs atol = atol rtol = rtol @test log(sol[17]) ≈ rhs atol = atol rtol = rtol @test abs(sol[18] - 11) ≈ rhs atol = atol rtol = rtol @test cos(sol[19]) ≈ 1.0 atol = atol rtol = rtol @test sin(sol[20]) ≈ 0.0 atol = atol rtol = rtol @test isfinite(sin(sol[21])) end @testset "add nonlinear constraint after solve" begin optimizer = SCIP.Optimizer(; display_verblevel=0) MOI.set(optimizer, MOI.RawOptimizerAttribute("display/verblevel"), 0) x, y = MOI.add_variables(optimizer, 2) data1 = MOI.NLPBlockData( [MOI.NLPBoundsPair(rhs, rhs) for rhs in [1.0, 2.0]], ExprEvaluator([:(x[$x] == 1.0), :(x[$y] == 2.0)]), false, ) MOI.set(optimizer, MOI.NLPBlock(), data1) MOI.optimize!(optimizer) data2 = MOI.NLPBlockData( [MOI.NLPBoundsPair(rhs, rhs) for rhs in [1.0, 2.0, 3.0]], ExprEvaluator([ :(x[$x] == 1.0), :(x[$y] == 2.0), :(x[$x] + x[$y] == 3.0), ]), false, ) MOI.set(optimizer, MOI.NLPBlock(), data2) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
1844
using MathOptInterface const MOI = MathOptInterface const MOIB = MOI.Bridges const MOIT = MOI.Test const BRIDGED = MOIB.full_bridge_optimizer(SCIP.Optimizer(; display_verblevel=0), Float64) const CONFIG_BRIDGED = MOIT.Config(; atol=5e-3, rtol=1e-4, exclude=Any[ MOI.ConstraintDual, MOI.ConstraintName, MOI.DualObjectiveValue, MOI.VariableBasisStatus, MOI.ConstraintBasisStatus, ], ) @testset "MOI unit tests" begin excluded = copy(MOI_BASE_EXCLUDED) append!( excluded, [ "test_linear_Interval_inactive", # Can not delete variable while model contains constraints "test_linear_integration", "test_basic_ScalarQuadraticFunction_ZeroOne", "test_basic_VectorAffineFunction_NormOneCone", "test_basic_VectorAffineFunction_SOS1", "test_basic_VectorAffineFunction_SOS2", "test_basic_VectorQuadraticFunction_NormOneCone", "test_basic_VectorQuadraticFunction_SOS1", "test_basic_VectorQuadraticFunction_SOS2", "test_quadratic_duplicate_terms", # Can not delete variable while model contains constraints "test_quadratic_nonhomogeneous", # unsupported by bridge "ScalarAffineFunction_ZeroOne", "test_model_delete", "test_conic_GeometricMeanCone_Vector", "test_basic_VectorOfVariables_GeometricMeanCone", "test_basic_VectorQuadraticFunction_GeometricMeanCone", "test_basic_VectorAffineFunction_GeometricMeanCone", "test_variable_delete_SecondOrderCone", "test_linear_Indicator_ON_ZERO", ], ) MOIT.runtests( BRIDGED, CONFIG_BRIDGED; warn_unsupported=false, exclude=excluded, ) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
1144
using MathOptInterface const MOI = MathOptInterface @testset "MOI_wrapper_cached" begin MOI.Test.runtests( MOI.Bridges.full_bridge_optimizer( MOI.Utilities.CachingOptimizer( MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()), SCIP.Optimizer(; display_verblevel=0), ), Float64, ), MOI.Test.Config(; atol=5e-3, rtol=1e-4, exclude=Any[ MOI.ConstraintDual, MOI.DualObjectiveValue, MOI.VariableBasisStatus, MOI.ConstraintBasisStatus, ], ); exclude=[ # Upstream problem in MOI.Test: InexactError: trunc(Int64, 1.0e20) "test_cpsat_CountGreaterThan", # SCIP does not support nonlinear objective functions. "test_nonlinear_hs071_NLPBlockDual", "test_nonlinear_invalid", "test_nonlinear_objective", "test_nonlinear_objective_and_moi_objective_test", "test_linear_Indicator_ON_ZERO", # error on SCIP ], ) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
913
using MathOptInterface const MOI = MathOptInterface const MOIT = MOI.Test const OPTIMIZER = SCIP.Optimizer(; display_verblevel=0) const CONFIG_DIRECT = MOIT.Config(; atol=5e-3, rtol=1e-4, exclude=Any[ MOI.ConstraintDual, MOI.ConstraintName, MOI.DualObjectiveValue, MOI.VariableBasisStatus, MOI.ConstraintBasisStatus, ], ) @testset "MOI unit tests" begin excluded = copy(MOI_BASE_EXCLUDED) append!( excluded, [ "test_linear_integration", # Can not delete variable while model contains constraints "test_basic_VectorOfVariables_SecondOrderCone", "test_conic_SecondOrderCone_nonnegative_post_bound", "test_variable_delete_SecondOrderCone", ], ) MOIT.runtests( OPTIMIZER, CONFIG_DIRECT; warn_unsupported=false, exclude=excluded, ) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
2605
using SCIP import MathOptInterface as MOI using Test using LinearAlgebra using Random Random.seed!(42) """ Select the most fractional variable to branch on. """ mutable struct MostFractional <: SCIP.AbstractBranchingRule ncalls::Int end MostFractional() = MostFractional(0) # we only specialize the branching on LP rule function SCIP.branch(branchrule::MostFractional, scip, allow_additional_constraints, type::SCIP.BranchingLP) branchrule.ncalls += 1 (candidates, _, candidates_fractionalities, nprio, nimplied) = SCIP.get_branching_candidates(scip) candidate_idx = argmax(idx -> abs(candidates_fractionalities[idx] - 0.5), 1:nprio) var = candidates[candidate_idx] SCIP.branch_on_candidate!(scip, var) return (SCIP.SCIP_OKAY, SCIP.SCIP_BRANCHED) end @testset "branchrule" begin # removing presolving and cuts to solve a non-trivial problem that requires some branching o = SCIP.Optimizer(; presolving_maxrounds=0) MOI.set(o, MOI.RawOptimizerAttribute("separating/maxrounds"), 0) MOI.set(o, MOI.RawOptimizerAttribute("separating/maxcutsroot"), 0) MOI.set(o, MOI.RawOptimizerAttribute("separating/maxaddrounds"), 0) MOI.set(o, MOI.Silent(), true) branchrule = MostFractional() name = "my_branchrule" description = "a most infeasible branching rule" priority = 15_000 SCIP.include_branchrule( o, branchrule, name=name, description=description, priority=priority, ) branchrule_pointer = o.inner.branchrule_storage[branchrule] @test unsafe_string(SCIP.LibSCIP.SCIPbranchruleGetName(branchrule_pointer)) == name @test unsafe_string(SCIP.LibSCIP.SCIPbranchruleGetDesc(branchrule_pointer)) == description @test SCIP.LibSCIP.SCIPbranchruleGetPriority(branchrule_pointer) == priority @test SCIP.LibSCIP.SCIPbranchruleGetData(branchrule_pointer) == pointer_from_objref(branchrule) n = 20 x = MOI.add_variables(o, n) MOI.add_constraint.(o, x, MOI.Integer()) MOI.add_constraint.(o, x, MOI.GreaterThan(-0.1)) MOI.add_constraint.(o, x, MOI.LessThan(2.3)) MOI.add_constraint(o, sum(x; init=0.0), MOI.LessThan(12.5)) for _ in 1:10 MOI.add_constraint( o, 2.0 * dot(rand(n), x), MOI.LessThan(10.0 + 2 * rand()), ) end func = -dot(rand(n), x) MOI.set(o, MOI.ObjectiveFunction{typeof(func)}(), func) MOI.set(o, MOI.ObjectiveSense(), MOI.MIN_SENSE) MOI.optimize!(o) @test MOI.get(o, MOI.TerminationStatus()) == MOI.OPTIMAL @test branchrule.ncalls > 0 end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
3690
@testset "dummy conshdlr (always satisfied, no constraint)" begin # create an empty problem o = SCIP.Optimizer() MOI.set(o, MOI.Silent(), true) SCIP.set_parameter(o.inner, "display/verblevel", 0) # add the constraint handler ch = Dummy.DummyConsHdlr() SCIP.include_conshdlr( o.inner.scip[], o.inner.conshdlrs, ch; needs_constraints=false, ) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(o.inner.scip[]) @test ch.check_called >= 1 @test ch.enfo_called == 0 @test ch.lock_called == 1 # free the problem finalize(o) end @testset "dummy conshdlr (always satisfied, with constraint)" begin # create an empty problem o = SCIP.Optimizer() MOI.set(o, MOI.Silent(), true) # add the constraint handler ch = Dummy.DummyConsHdlr() SCIP.include_conshdlr( o.inner.scip[], o.inner.conshdlrs, ch; needs_constraints=true, ) # add dummy constraint cr = SCIP.add_constraint(o.inner, ch, Dummy.DummyCons()) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(o.inner.scip[]) @test ch.check_called >= 1 @test ch.enfo_called == 0 @test ch.lock_called == 1 # free the problem finalize(o) end @testset "dummy conshdlr (always satisfied, no constraint, but needs it)" begin # create an empty problem o = SCIP.Optimizer() MOI.set(o, MOI.Silent(), true) # add the constraint handler ch = Dummy.DummyConsHdlr() SCIP.include_conshdlr( o.inner.scip[], o.inner.conshdlrs, ch; needs_constraints=true, ) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(o.inner.scip[]) @test ch.check_called == 0 @test ch.enfo_called == 0 @test ch.lock_called == 0 # free the problem finalize(o) end @testset "never satisfied conshdlr (does not need constraint)" begin # create an empty problem o = SCIP.Optimizer() MOI.set(o, MOI.Silent(), true) # add the constraint handler ch = NeverSatisfied.NSCH() SCIP.include_conshdlr( o.inner.scip[], o.inner.conshdlrs, ch; needs_constraints=false, ) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(o.inner.scip[]) @test ch.check_called >= 1 @test ch.enfo_called in 0:1 # depends on SCIP presolver behavior @test ch.lock_called == 1 # free the problem finalize(o) end @testset "never satisfied conshdlr (needs constraint but does not have it)" begin # create an empty problem o = SCIP.Optimizer() MOI.set(o, MOI.Silent(), true) # add the constraint handler ch = NeverSatisfied.NSCH() SCIP.include_conshdlr( o.inner.scip[], o.inner.conshdlrs, ch; needs_constraints=true, ) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(o.inner.scip[]) @test ch.check_called == 0 @test ch.enfo_called == 0 @test ch.lock_called == 0 # free the problem finalize(o) end @testset "never satisfied conshdlr (needs constraint and has one)" begin # create an empty problem o = SCIP.Optimizer() MOI.set(o, MOI.Silent(), true) # add the constraint handler ch = NeverSatisfied.NSCH() SCIP.include_conshdlr( o.inner.scip[], o.inner.conshdlrs, ch; needs_constraints=true, ) # add one constraint cr = SCIP.add_constraint(o.inner, ch, NeverSatisfied.Cons()) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(o.inner.scip[]) @test ch.check_called >= 1 @test ch.enfo_called == 1 @test ch.lock_called == 1 # free the problem finalize(o) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
6451
module Dummy using SCIP # Define a minimal no-op constraint handler. # Needs to be mutable for `pointer_from_objref` to work. mutable struct DummyConsHdlr <: SCIP.AbstractConstraintHandler check_called::Int64 enfo_called::Int64 lock_called::Int64 DummyConsHdlr() = new(0, 0, 0) end # Implement only the fundamental callbacks: function SCIP.check( ch::DummyConsHdlr, constraints::Array{Ptr{SCIP.SCIP_CONS}}, sol::Ptr{SCIP.SCIP_SOL}, checkintegrality::Bool, checklprows::Bool, printreason::Bool, completely::Bool, ) ch.check_called += 1 return SCIP.SCIP_FEASIBLE end function SCIP.enforce_lp_sol( ch::DummyConsHdlr, constraints::Array{Ptr{SCIP.SCIP_CONS}}, nusefulconss::Cint, solinfeasible::Bool, ) ch.enfo_called += 1 return SCIP.SCIP_FEASIBLE end function SCIP.enforce_pseudo_sol( ch::DummyConsHdlr, constraints::Array{Ptr{SCIP.SCIP_CONS}}, nusefulconss::Cint, solinfeasible::Bool, objinfeasible::Bool, ) ch.enfo_called += 1 return SCIP.SCIP_FEASIBLE end function SCIP.lock( ch::DummyConsHdlr, constraint::Ptr{SCIP.SCIP_CONS}, locktype::SCIP.SCIP_LOCKTYPE, nlockspos::Cint, nlocksneg::Cint, ) ch.lock_called += 1 end # Corresponding, empty constraint (data) object mutable struct DummyCons <: SCIP.AbstractConstraint{DummyConsHdlr} end end # module Dummy module NeverSatisfied using SCIP mutable struct NSCH <: SCIP.AbstractConstraintHandler check_called::Int64 enfo_called::Int64 lock_called::Int64 NSCH() = new(0, 0, 0) end function SCIP.check( ch::NSCH, constraints, sol, checkintegrality, checklprows, printreason, completely, ) ch.check_called += 1 return SCIP.SCIP_INFEASIBLE end function SCIP.enforce_lp_sol(ch::NSCH, constraints, nusefulconss, solinfeasible) ch.enfo_called += 1 return SCIP.SCIP_INFEASIBLE end function SCIP.enforce_pseudo_sol( ch::NSCH, constraints, nusefulconss, solinfeasible, objinfeasible, ) ch.enfo_called += 1 return SCIP.SCIP_INFEASIBLE end function SCIP.lock(ch::NSCH, constraint, locktype, nlockspos, nlocksneg) ch.lock_called += 1 end # Corresponding, empty constraint (data) object mutable struct Cons <: SCIP.AbstractConstraint{NSCH} end end # module AlwaysSatisfied module NaiveAllDiff using MathOptInterface using SCIP const MOI = MathOptInterface mutable struct NADCH <: SCIP.AbstractConstraintHandler scip::SCIP.Optimizer # for SCIP* and var maps end # Constraint data, referencing variables of a single constraint. mutable struct NADCons <: SCIP.AbstractConstraint{NADCH} variables::Vector{MOI.VariableIndex} end # Helper function used in several callbacks function anyviolated(ch, constraints, sol=C_NULL) for cons_::Ptr{SCIP.SCIP_CONS} in constraints cons::NADCons = SCIP.user_constraint(cons_) # extract solution values values = SCIP.sol_values(ch.scip, cons.variables, sol) # check for constraint violation if !allunique(values) return true end end return false end function SCIP.check( ch::NADCH, constraints, sol, checkintegrality, checklprows, printreason, completely, ) if anyviolated(ch, constraints, sol) return SCIP.SCIP_INFEASIBLE else return SCIP.SCIP_FEASIBLE end end function SCIP.enforce_lp_sol( ch::NADCH, constraints, nusefulconss, solinfeasible, ) if anyviolated(ch, constraints, C_NULL) return SCIP.SCIP_INFEASIBLE else return SCIP.SCIP_FEASIBLE end end function SCIP.enforce_pseudo_sol( ch::NADCH, constraints, nusefulconss, solinfeasible, objinfeasible, ) if anyviolated(ch, constraints, C_NULL) return SCIP.SCIP_INFEASIBLE else return SCIP.SCIP_FEASIBLE end end function SCIP.lock(ch::NADCH, constraint, locktype, nlockspos, nlocksneg) cons::NADCons = SCIP.user_constraint(constraint) # look all variables in both directions for vi in cons.variables # TODO: understand why lock is called during SCIPfree, after the # constraint should have been deleted already. Does it mean we should # implement CONSTRANS? var_::Ptr{SCIP.SCIP_VAR} = SCIP.var(ch.scip, vi) var_ != C_NULL || continue # avoid segfault! SCIP.@SCIP_CALL SCIP.SCIPaddVarLocksType( ch.scip, var_, locktype, nlockspos + nlocksneg, nlockspos + nlocksneg, ) end end end # module NaiveAllDiff module NoGoodCounter using MathOptInterface using SCIP const MOI = MathOptInterface mutable struct Counter <: SCIP.AbstractConstraintHandler scip::SCIP.Optimizer # for SCIP* and var maps variables::Vector{MOI.VariableIndex} solutions::Set{Array{Float64}} Counter(scip, variables) = new(scip, variables, Set()) end function SCIP.check( ch::Counter, constraints, sol, checkintegrality, checklprows, printreason, completely, ) return SCIP.SCIP_INFEASIBLE end function enforce(ch::Counter) values = SCIP.sol_values(ch.scip, ch.variables) # Store solution if values in ch.solutions # Getting the same solution twice? return SCIP.SCIP_INFEASIBLE end push!(ch.solutions, values) # Add no-good constraint: sum_zeros(x) + sum_ones(1-x) >= 1 zeros = values .≈ 0.0 ones = values .≈ 1.0 others = .!zeros .& .!ones if any(others) error("Found non-binary solution value for $(vars[others])") end terms = vcat( [MOI.ScalarAffineTerm(1.0, vi) for vi in ch.variables[zeros]], [MOI.ScalarAffineTerm(-1.0, vi) for vi in ch.variables[ones]], ) ci = MOI.add_constraint( ch.scip, MOI.ScalarAffineFunction(terms, 0.0), MOI.GreaterThan(1.0 - sum(ones)), ) return SCIP.SCIP_CONSADDED end function SCIP.enforce_lp_sol( ch::Counter, constraints, nusefulconss, solinfeasible, ) @assert length(constraints) == 0 return enforce(ch) end function SCIP.enforce_pseudo_sol( ch::Counter, constraints, nusefulconss, solinfeasible, objinfeasible, ) @assert length(constraints) == 0 return enforce(ch) end function SCIP.lock(ch::Counter, constraint, locktype, nlockspos, nlocksneg) end end # module NoGoodCounter
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
5840
using MathOptInterface const MOI = MathOptInterface # Test, whether the cut callback is actually called and whether # `callback_value` works as intended. @testset "obtaining the LP-solution" begin atol, rtol = 1e-6, 1e-6 # create an empty problem optimizer = SCIP.Optimizer() inner = optimizer.inner sepa_set_scip_parameters((par, val) -> SCIP.set_parameter(inner, par, val)) # add variables x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # add constraint: x + y ≤ 1.5 MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.5), ) # maximize x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) calls = 0 x_val::Float64 = -1 y_val::Float64 = -1 function cutcallback(cb_data) x_val = MOI.get( optimizer, MOI.CallbackVariablePrimal{SCIP.CutCbData}(cb_data), x, ) y_val = MOI.get( optimizer, MOI.CallbackVariablePrimal{SCIP.CutCbData}(cb_data), y, ) calls += 1 end MOI.set(optimizer, MOI.UserCutCallback(), cutcallback) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(inner.scip[]) # The cut callback was called and obtaining the LP-solution worked. @test calls >= 1 @test x_val + y_val >= 1.0 - min(atol, 1.0 * rtol) # SCIP found an optimal solution @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 1.0 atol = atol rtol = rtol # free the problem finalize(inner) end # Test, whether adding cuts within cut callbacks via `submit` works [1/2]. @testset "cutting one optimal solution" begin atol, rtol = 1e-6, 1e-6 # create an empty problem optimizer = SCIP.Optimizer() inner = optimizer.inner sepa_set_scip_parameters((par, val) -> SCIP.set_parameter(inner, par, val)) # add variables x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # add constraint: x + y ≤ 1.5 MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.5), ) # maximize x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), 1.0 * x + 1.0 * y, ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) calls = 0 function cutcallback(cb_data) MOI.submit( optimizer, MOI.UserCut{SCIP.CutCbData}(cb_data), 1.0 * x, MOI.LessThan(0.0), ) calls += 1 end MOI.set(optimizer, MOI.UserCutCallback(), cutcallback) # solve the problem MOI.optimize!(optimizer) # The cut callback was called. @test calls >= 1 # SCIP found the single remaining optimal solution @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 1.0 atol = atol rtol = rtol end # Test, whether adding cuts within cut callbacks via `submit` works [2/2]. @testset "cutting another optimal solution" begin atol, rtol = 1e-6, 1e-6 # create an empty problem optimizer = SCIP.Optimizer() inner = optimizer.inner sepa_set_scip_parameters((par, val) -> SCIP.set_parameter(inner, par, val)) # add variables x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # add constraint: x + y ≤ 1.5 MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.5), ) # maximize x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) calls = 0 function cutcallback(cb_data) MOI.submit( optimizer, MOI.UserCut{SCIP.CutCbData}(cb_data), MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.([1.0], [y]), 0.0), MOI.LessThan(0.0), ) calls += 1 end MOI.set(optimizer, MOI.UserCutCallback(), cutcallback) # solve the problem MOI.optimize!(optimizer) # The cut callback was called. @test calls >= 1 # SCIP found the single remaining optimal solution @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 0.0 atol = atol rtol = rtol end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
6718
using SCIP import MathOptInterface const MOI = MathOptInterface using Test using LinearAlgebra using Random Random.seed!(42) """ Selects cut by efficacy only, selects up to `nmax_cuts` cuts. """ mutable struct EfficacyCutSelector <: SCIP.AbstractCutSelector o::SCIP.Optimizer nmax_cuts::Int ncalls::Int end function SCIP.select_cuts( cutsel::EfficacyCutSelector, scip, cuts::Vector{Ptr{SCIP.SCIP_ROW}}, forced_cuts::Vector{Ptr{SCIP.SCIP_ROW}}, root::Bool, maxnslectedcuts::Integer, ) function efficacy_function(cut) return SCIP.LibSCIP.SCIPgetCutEfficacy(scip, C_NULL, cut) end sort!(cuts; by=efficacy_function, rev=true) nselected_cuts = min(cutsel.nmax_cuts, maxnslectedcuts) nselected_cuts = max(nselected_cuts, 0) nselected_cuts = min(nselected_cuts, length(cuts)) cutsel.ncalls += 1 return (SCIP.SCIP_OKAY, nselected_cuts, SCIP.SCIP_SUCCESS) end @testset "test cut selector" begin # removing presolving to solve a non-trivial problem that requires some separation o = SCIP.Optimizer(; presolving_maxrounds=0) MOI.set(o, MOI.Silent(), true) cutsel = EfficacyCutSelector(o, 10, 0) name = "my_cut_selector" description = "a selector using efficacy only" priority = 15_000 SCIP.include_cutsel( o, cutsel; name=name, description=description, priority=priority, ) cutsel_pointer = o.inner.cutsel_storage[cutsel] @test unsafe_string(SCIP.LibSCIP.SCIPcutselGetName(cutsel_pointer)) == name @test unsafe_string(SCIP.LibSCIP.SCIPcutselGetDesc(cutsel_pointer)) == description @test SCIP.LibSCIP.SCIPcutselGetPriority(cutsel_pointer) == priority @test SCIP.LibSCIP.SCIPcutselGetData(cutsel_pointer) == pointer_from_objref(cutsel) x = MOI.add_variables(o, 10) MOI.add_constraint.(o, x, MOI.Integer()) MOI.add_constraint.(o, x, MOI.GreaterThan(-0.1)) MOI.add_constraint.(o, x, MOI.LessThan(2.3)) MOI.add_constraint(o, sum(x; init=0.0), MOI.LessThan(12.5)) for _ in 1:5 MOI.add_constraint( o, 2.0 * dot(rand(10), x), MOI.LessThan(10.0 + 2 * rand()), ) end func = -dot(rand(10), x) MOI.set(o, MOI.ObjectiveFunction{typeof(func)}(), func) MOI.set(o, MOI.ObjectiveSense(), MOI.MIN_SENSE) MOI.optimize!(o) @test MOI.get(o, MOI.TerminationStatus()) == MOI.OPTIMAL @test cutsel.ncalls > 0 end # select by removing cuts that are too parallel to a forced cut mutable struct SecondSelector <: SCIP.AbstractCutSelector o::SCIP.Optimizer nmax_cuts::Int ncalls::Int min_orthogonality::Float64 end function SCIP.select_cuts( cutsel::SecondSelector, scip, cuts::Vector{Ptr{SCIP.SCIP_ROW}}, forced_cuts::Vector{Ptr{SCIP.SCIP_ROW}}, root::Bool, maxnslectedcuts::Integer, ) rem_cuts = Set{Ptr{SCIP.SCIP_ROW}}() for cut in cuts for fcut in forced_cuts o_score = SCIP.LibSCIP.SCIProwGetOrthogonality(cut, fcut, 'e') if o_score < cutsel.min_orthogonality push!(rem_cuts, cut) break end end end function sorting_function(cut) if cut in rem_cuts return -1.0 end return SCIP.LibSCIP.SCIPgetCutEfficacy(scip, C_NULL, cut) end sort!(cuts; by=sorting_function, rev=true) nselected_cuts = min(cutsel.nmax_cuts, maxnslectedcuts) nselected_cuts = max(nselected_cuts, 0) nselected_cuts = min(nselected_cuts, length(cuts) - length(rem_cuts)) cutsel.ncalls += 1 return (SCIP.SCIP_OKAY, nselected_cuts, SCIP.SCIP_SUCCESS) end @testset "test cut selector parallelism" begin # removing presolving to solve a non-trivial problem that requires some separation o = SCIP.Optimizer(; presolving_maxrounds=0) MOI.set(o, MOI.Silent(), true) cutsel = SecondSelector(o, 10, 0, 0.05) name = "my_cut_selector_parallelism" description = "a selector using efficacy and parallelism" priority = 15_000 SCIP.include_cutsel( o, cutsel; name=name, description=description, priority=priority, ) cutsel_pointer = o.inner.cutsel_storage[cutsel] @test unsafe_string(SCIP.LibSCIP.SCIPcutselGetName(cutsel_pointer)) == name @test unsafe_string(SCIP.LibSCIP.SCIPcutselGetDesc(cutsel_pointer)) == description @test SCIP.LibSCIP.SCIPcutselGetPriority(cutsel_pointer) == priority @test SCIP.LibSCIP.SCIPcutselGetData(cutsel_pointer) == pointer_from_objref(cutsel) x = MOI.add_variables(o, 10) MOI.add_constraint.(o, x, MOI.Integer()) MOI.add_constraint.(o, x, MOI.GreaterThan(-0.1)) MOI.add_constraint.(o, x, MOI.LessThan(2.3)) MOI.add_constraint(o, sum(x; init=0.0), MOI.LessThan(12.5)) for _ in 1:5 MOI.add_constraint( o, 2.0 * dot(rand(10), x), MOI.LessThan(10.0 + 2 * rand()), ) end func = -dot(rand(10), x) MOI.set(o, MOI.ObjectiveFunction{typeof(func)}(), func) MOI.set(o, MOI.ObjectiveSense(), MOI.MIN_SENSE) MOI.optimize!(o) @test MOI.get(o, MOI.TerminationStatus()) == MOI.OPTIMAL @test cutsel.ncalls > 0 end @testset "test default hybrid cut selector" begin o = SCIP.Optimizer(; presolving_maxrounds=0) MOI.set(o, MOI.Silent(), true) cutsel = SCIP.HybridCutSelector() name = "hybrid_cut_selector" description = "default cut selector" priority = 15_000 SCIP.include_cutsel( o, cutsel; name=name, description=description, priority=priority, ) cutsel_pointer = o.inner.cutsel_storage[cutsel] @test unsafe_string(SCIP.LibSCIP.SCIPcutselGetName(cutsel_pointer)) == name @test unsafe_string(SCIP.LibSCIP.SCIPcutselGetDesc(cutsel_pointer)) == description @test SCIP.LibSCIP.SCIPcutselGetPriority(cutsel_pointer) == priority @test SCIP.LibSCIP.SCIPcutselGetData(cutsel_pointer) == pointer_from_objref(cutsel) x = MOI.add_variables(o, 10) MOI.add_constraint.(o, x, MOI.Integer()) MOI.add_constraint.(o, x, MOI.GreaterThan(-0.1)) MOI.add_constraint.(o, x, MOI.LessThan(2.3)) MOI.add_constraint(o, sum(x; init=0.0), MOI.LessThan(12.5)) for _ in 1:5 MOI.add_constraint( o, 2.0 * dot(rand(10), x), MOI.LessThan(10.0 + 2 * rand()), ) end func = -dot(rand(10), x) MOI.set(o, MOI.ObjectiveFunction{typeof(func)}(), func) MOI.set(o, MOI.ObjectiveSense(), MOI.MIN_SENSE) MOI.optimize!(o) @test MOI.get(o, MOI.TerminationStatus()) == MOI.OPTIMAL end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
2446
# Test raw wrapper with direct library calls @testset "create small problem and solve" begin scip__ = Ref{Ptr{SCIP.SCIP_}}() # SCIP** rc = SCIP.SCIPcreate(scip__) @test rc == SCIP.SCIP_OKAY scip_ = scip__[] # dereference to SCIP* @test scip_ != C_NULL rc = SCIP.SCIPincludeDefaultPlugins(scip_) @test rc == SCIP.SCIP_OKAY # disable output rc = SCIP.SCIPsetIntParam(scip_, "display/verblevel", 0) @test rc == SCIP.SCIP_OKAY # create problem rc = SCIP.SCIPcreateProbBasic(scip_, "") @test rc == SCIP.SCIP_OKAY # add variable: x >= 0, objcoef: 1 var__ = Ref{Ptr{SCIP.SCIP_VAR}}() rc = SCIP.SCIPcreateVarBasic( scip_, var__, "x", 0.0, SCIP.SCIPinfinity(scip_), 1.0, SCIP.SCIP_VARTYPE_CONTINUOUS, ) @test rc == SCIP.SCIP_OKAY var_ = var__[] @test var_ != C_NULL rc = SCIP.SCIPaddVar(scip_, var_) @test rc == SCIP.SCIP_OKAY # add constraint: 2x >= 3 ( really: 3 <= 2 * x <= inf ) cons__ = Ref{Ptr{SCIP.SCIP_CONS}}() rc = SCIP.SCIPcreateConsBasicLinear( scip_, cons__, "c", 0, C_NULL, C_NULL, 3.0, SCIP.SCIPinfinity(scip_), ) @test rc == SCIP.SCIP_OKAY cons_ = cons__[] @test cons_ != C_NULL rc = SCIP.SCIPaddCoefLinear(scip_, cons_, var_, 2.0) @test rc == SCIP.SCIP_OKAY rc = SCIP.SCIPaddCons(scip_, cons_) @test rc == SCIP.SCIP_OKAY # solve problem rc = SCIP.SCIPsolve(scip_) @test rc == SCIP.SCIP_OKAY # check solution value sol_ = SCIP.SCIPgetBestSol(scip_) @test sol_ != C_NULL val = SCIP.SCIPgetSolVal(scip_, sol_, var_) @test val ≈ 3.0 / 2.0 # release variables and solver rc = SCIP.SCIPreleaseCons(scip_, cons__) @test rc == SCIP.SCIP_OKAY rc = SCIP.SCIPreleaseVar(scip_, var__) @test rc == SCIP.SCIP_OKAY rc = SCIP.SCIPfree(scip__) @test rc == SCIP.SCIP_OKAY end @testset "SCIP_CALL macro (@SCIP_CALL)" begin # should do nothing SCIP.@SCIP_CALL SCIP.SCIP_OKAY @test_throws ErrorException SCIP.@SCIP_CALL SCIP.SCIP_ERROR f() = SCIP.SCIP_OKAY g(args...) = SCIP.SCIP_ERROR SCIP.@SCIP_CALL f() h() = SCIP.@SCIP_CALL(g(1, 2)) @test_throws ErrorException("g() yielded SCIP code SCIP_ERROR") SCIP.@SCIP_CALL g() @test_throws ErrorException("g(1, 2) yielded SCIP code SCIP_ERROR") h() end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
3425
import MathOptInterface as MOI using SCIP using LinearAlgebra using Test mutable struct ZeroHeuristic <: SCIP.Heuristic end function SCIP.find_primal_solution(scip, ::ZeroHeuristic, heurtiming, nodeinfeasible::Bool, heur_ptr) @assert SCIP.SCIPhasCurrentNodeLP(scip) == SCIP.TRUE result = SCIP.SCIP_DIDNOTRUN sol = SCIP.create_empty_scipsol(scip, heur_ptr) vars = SCIP.SCIPgetVars(scip) nvars = SCIP.SCIPgetNVars(scip) var_vec = unsafe_wrap(Array, vars, nvars) for var in var_vec SCIP.@SCIP_CALL SCIP.SCIPsetSolVal( scip, sol, var, 0.0, ) end stored = Ref{SCIP.SCIP_Bool}(SCIP.FALSE) SCIP.@SCIP_CALL SCIP.SCIPtrySolFree( scip, Ref(sol), SCIP.FALSE, SCIP.FALSE, SCIP.TRUE, SCIP.TRUE, SCIP.TRUE, stored, ) result = if stored[] != SCIP.TRUE SCIP.SCIP_DIDNOTFIND else SCIP.SCIP_FOUNDSOL end return (SCIP.SCIP_OKAY, result) end @testset "Basic heuristic properties" begin o = SCIP.Optimizer(; presolving_maxrounds=0, display_verblevel=0) name = "zero_heuristic" description = "description" priority = 1 heur = ZeroHeuristic() SCIP.include_heuristic(o, heur, name=name, description=description, priority=priority) heur_pointer = o.inner.heuristic_storage[heur] @test unsafe_string(SCIP.LibSCIP.SCIPheurGetName(heur_pointer)) == name @test unsafe_string(SCIP.LibSCIP.SCIPheurGetDesc(heur_pointer)) == description @test SCIP.LibSCIP.SCIPheurGetPriority(heur_pointer) == priority @test SCIP.LibSCIP.SCIPheurGetData(heur_pointer) == pointer_from_objref(heur) x = MOI.add_variables(o, 10) MOI.add_constraint.(o, x, MOI.Integer()) MOI.add_constraint.(o, x, MOI.GreaterThan(-0.1)) MOI.add_constraint.(o, x, MOI.LessThan(2.3)) MOI.add_constraint(o, sum(x; init=0.0), MOI.LessThan(12.5)) for _ in 1:5 MOI.add_constraint( o, 2.0 * dot(rand(10), x), MOI.LessThan(10.0 + 2 * rand()), ) end func = -dot(rand(10), x) MOI.set(o, MOI.ObjectiveFunction{typeof(func)}(), func) MOI.set(o, MOI.ObjectiveSense(), MOI.MIN_SENSE) MOI.optimize!(o) @test MOI.get(o, MOI.TerminationStatus()) == MOI.OPTIMAL end @testset "Heuristic through MOI" begin o = SCIP.Optimizer(; presolving_maxrounds=0, display_verblevel=0) n = 10 x = MOI.add_variables(o, n) MOI.add_constraint.(o, x, MOI.ZeroOne()) MOI.add_constraint( o, sum(x; init=0.0), MOI.LessThan(3.0), ) MOI.set(o, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), dot(rand(n), x)) MOI.set(o, MOI.ObjectiveSense(), MOI.MAX_SENSE) ncalls = Ref(0) function heuristic_callback(callback_data::SCIP.HeuristicCbData) # LP solution x_frac = MOI.get(o, MOI.CallbackVariablePrimal(callback_data), x) # setting heuristic solution with three values at 1 values = 0 * x_frac values[findmax(x_frac)[2]] = 1.0 values[1] = 1.0 values[2] = 1.0 MOI.submit( o, MOI.HeuristicSolution(callback_data), x, values, ) global ncalls[] +=1 end MOI.set(o, MOI.HeuristicCallback(), heuristic_callback) MOI.optimize!(o) @test ncalls[] > 0 end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
2508
using Test using SCIP using SCIP_jll using SCIP_PaPILO_jll @static if VERSION >= v"1.7" import LinearAlgebra, OpenBLAS32_jll LinearAlgebra.BLAS.lbt_forward(OpenBLAS32_jll.libopenblas_path) end @show(@eval(SCIP, libscip) == SCIP_jll.libscip) @show( SCIP_PaPILO_jll.is_available() && @eval(SCIP, libscip) == SCIP_PaPILO_jll.libscip ) @show SCIP.SCIP_versionnumber() @testset "MathOptInterface nonlinear expressions" begin include("MOI_nonlinear_exprs.jl") end @testset "direct library calls" begin include("direct_library_calls.jl") end @testset "managed memory" begin include("scip_data.jl") end # new type definitions in module (needs top level) include("conshdlr_support.jl") @testset "constraint handlers" begin include("conshdlr.jl") end include("sepa_support.jl") @testset "separators" begin include("sepa.jl") end @testset "cut callbacks" begin include("cutcallback.jl") end @testset "branching rule" begin include("branchrule.jl") end @testset "heuristic" begin include("heuristic.jl") end const MOI_BASE_EXCLUDED = [ "Indicator_LessThan", # indicator must be binary error in SCIP "Indicator_ACTIVATE_ON_ZERO", # odd MOI bug? "test_constraint_get_ConstraintIndex", # accessing constraint from string name "BoundAlreadySet", # see TODO, "ScalarAffineFunction_ConstraintName", # get(::SCIP.Optimizer, ::Type{MathOptInterface.ConstraintIndex}, ::String) "duplicate_VariableName", # two identical variable names should error at get time "test_model_VariableName", # same issue "test_model_Name_VariableName_ConstraintName", "test_modification_delete_variables_in_a_batch", "test_modification_set_function_single_variable", "test_modification_set_scalaraffine_", "test_modification_set_singlevariable_", "test_modification_transform_", "test_nonlinear_", # None of tests provide expression graphs in the evaluator. "ObjectiveFunction_ScalarAffineFunction", # requires conversion of objective function "test_objective_set_via_modify", # ListOfModelAttributesSet ] @testset "MathOptInterface tests (direct)" begin include("MOI_wrapper_direct.jl") end @testset "MathOptInterface additional tests" begin include("MOI_additional.jl") end @testset "MathOptInterface tests (bridged)" begin include("MOI_wrapper_bridged.jl") end @testset "MathOptInterface tests (bridged & cached)" begin include("MOI_wrapper_cached.jl") end include("MOI_conshdlr.jl") include("cutsel.jl")
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
4775
# Test memory management using MathOptInterface @testset "create and manual free" begin o = SCIP.Optimizer() @test o.inner.scip[] != C_NULL SCIP.free_scip(o) @test o.inner.scip[] == C_NULL end @testset "create, add var and cons, and manual free" begin o = SCIP.Optimizer() @test o.inner.scip[] != C_NULL x = SCIP.add_variable(o.inner) y = SCIP.add_variable(o.inner) c = SCIP.add_linear_constraint(o.inner, [x, y], [2.0, 3.0], 1.0, 9.0) SCIP.free_scip(o) @test o.inner.scip[] == C_NULL end @testset "create and semi-manual free" begin o = SCIP.Optimizer() @test o.inner.scip[] != C_NULL finalize(o) @test o.inner.scip[] == C_NULL end @testset "create with vars and cons, and free" begin for i in 1:2 # run twice, with(out) solving o = SCIP.Optimizer() @test o.inner.scip[] != C_NULL SCIP.set_parameter(o.inner, "display/verblevel", 0) t = SCIP.add_variable(o.inner) # set lower bound for assertion in cons_soc.c SCIP.@SCIP_CALL SCIP.SCIPchgVarLb(o, SCIP.var(o.inner, t), 0.0) x = SCIP.add_variable(o.inner) y = SCIP.add_variable(o.inner) c = SCIP.add_linear_constraint(o.inner, [x, y], [2.0, 3.0], 1.0, 9.0) q = SCIP.add_quadratic_constraint( o.inner, [x], [2.0], [x, x], [x, y], [4.0, 5.0], 1.0, 9.0, ) s1 = SCIP.add_special_ordered_set_type1(o.inner, [t, x], [1.0, 2.0]) s2 = SCIP.add_special_ordered_set_type2(o.inner, [x, y], [1.0, 2.0]) # nonlinear: x^0.2 == 1 vi = MathOptInterface.VariableIndex(x.val) # n = SCIP.add_nonlinear_constraint(o.inner, :(x[$vi]^0.2 == 1.0), 1.0, 1.0) # indicator constraint: z = 1 ==> 𝟙^T [x, y] <= 1. z = SCIP.add_variable(o.inner) SCIP.@SCIP_CALL SCIP.SCIPchgVarType( o, SCIP.var(o.inner, z), SCIP.SCIP_VARTYPE_BINARY, Ref{SCIP.SCIP_Bool}(), ) SCIP.@SCIP_CALL SCIP.SCIPchgVarLb(o, SCIP.var(o.inner, z), 0.0) SCIP.@SCIP_CALL SCIP.SCIPchgVarUb(o, SCIP.var(o.inner, z), 1.0) ic = SCIP.add_indicator_constraint(o.inner, z, [x, y], ones(2), 1.0) if i == 2 # solve, but don't check results (this test is about memory mgmt) SCIP.@SCIP_CALL SCIP.SCIPsolve(o.inner.scip[]) end finalize(o) for var in values(o.inner.vars) @test var[] == C_NULL end for cons in values(o.inner.conss) @test cons[] == C_NULL end @test o.inner.scip[] == C_NULL end end @testset "create vars and cons, delete some, and free" begin for i in 1:2 # run twice, with(out) solving o = SCIP.Optimizer() @test o.inner.scip[] != C_NULL SCIP.set_parameter(o.inner, "display/verblevel", 0) x = SCIP.add_variable(o.inner) y = SCIP.add_variable(o.inner) z = SCIP.add_variable(o.inner) c = SCIP.add_linear_constraint(o.inner, [x, y], [2.0, 3.0], 1.0, 9.0) d = SCIP.add_linear_constraint(o.inner, [x, z], [2.0, 1.0], 2.0, 8.0) SCIP.delete(o.inner, d) SCIP.delete(o.inner, z) # only occured in constraint 'd' if i == 2 # solve, but don't check results (this test is about memory mgmt) SCIP.@SCIP_CALL SCIP.SCIPsolve(o) end finalize(o) for var in values(o.inner.vars) @test var[] == C_NULL end for cons in values(o.inner.conss) @test cons[] == C_NULL end @test o.inner.scip[] == C_NULL end end @testset "print statistics" begin o = SCIP.Optimizer() SCIP.set_parameter(o.inner, "display/verblevel", 0) x = SCIP.add_variable(o.inner) y = SCIP.add_variable(o.inner) z = SCIP.add_variable(o.inner) c = SCIP.add_linear_constraint(o.inner, [x, y], [2.0, 3.0], 1.0, 9.0) SCIP.@SCIP_CALL SCIP.SCIPsolve(o) @testset "$statistics_func" for statistics_func in map( x -> eval(:(SCIP.$x)), SCIP.STATISTICS_FUNCS, ) mktempdir() do dir filename = joinpath(dir, "statistics.txt") @test !isfile(filename) open(filename; write=true) do io redirect_stdout(io) do statistics_func(o.inner) end end @test isfile(filename) if statistics_func == SCIP.print_statistics # Ensure that at least `print_statistics` produces output # (Not all statistics functions do for this simple model.) @test filesize(filename) > 0 end end end end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
6773
using MathOptInterface const MOI = MathOptInterface # Test, whether the callback of the separator is called. @testset "DummySepa (no separation)" begin # create an empty problem optimizer = SCIP.Optimizer() inner = optimizer.inner sepa_set_scip_parameters((par, val) -> SCIP.set_parameter(inner, par, val)) # add variables x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # add constraint: x + y ≤ 1.5 MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.5), ) # maximize x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add the separator sepa = DummySepa.Sepa() SCIP.include_sepa(inner.scip[], inner.sepas, sepa) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(inner.scip[]) # the separator is called @test sepa.called >= 1 # free the problem finalize(inner) end # Test, whether adding cuts in `exec_lp` via `add_cut_sepa` works [1/2]. @testset "AddSingleCut (cut off one optimal solution)" begin atol, rtol = 1e-6, 1e-6 # create an empty problem optimizer = SCIP.Optimizer() inner = optimizer.inner sepa_set_scip_parameters((par, val) -> SCIP.set_parameter(inner, par, val)) # add variables x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # add constraint: x + y ≤ 1.5 MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.5), ) # maximize x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add the separator varrefs = [SCIP.VarRef(x.value)] coefs = [1.0] sepa = AddSingleCut.Sepa(inner, varrefs, coefs, 0.0, 0.0) SCIP.include_sepa(inner.scip[], inner.sepas, sepa) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(inner.scip[]) # SCIP found the single remaining optimal solution @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 1.0 atol = atol rtol = rtol # free the problem finalize(inner) end # Test, whether adding cuts in `exec_lp` via `add_cut_sepa` works [2/2]. @testset "AddSingleCut (cut off another optimal solution)" begin atol, rtol = 1e-6, 1e-6 # create an empty problem optimizer = SCIP.Optimizer() inner = optimizer.inner sepa_set_scip_parameters((par, val) -> SCIP.set_parameter(inner, par, val)) # add variables x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # add constraint: x + y ≤ 1.5 MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.5), ) # maximize x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add the separator varrefs = [SCIP.VarRef(y.value)] coefs = [1.0] sepa = AddSingleCut.Sepa(inner, varrefs, coefs, 0.0, 0.0) SCIP.include_sepa(inner.scip[], inner.sepas, sepa) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(inner.scip[]) # SCIP found the single remaining optimal solution @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 1.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 0.0 atol = atol rtol = rtol # free the problem finalize(inner) end # Test, whether we can cut the optimal solution. @testset "AddSingleCut (too strong cut)" begin atol, rtol = 1e-6, 1e-6 # create an empty problem optimizer = SCIP.Optimizer() inner = optimizer.inner sepa_set_scip_parameters((par, val) -> SCIP.set_parameter(inner, par, val)) # add variables x, y = MOI.add_variables(optimizer, 2) MOI.add_constraint(optimizer, x, MOI.ZeroOne()) MOI.add_constraint(optimizer, y, MOI.ZeroOne()) # add constraint: x + y ≤ 1.5 MOI.add_constraint( optimizer, MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), MOI.LessThan(1.5), ) # maximize x + y MOI.set( optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), MOI.ScalarAffineFunction( MOI.ScalarAffineTerm.([1.0, 1.0], [x, y]), 0.0, ), ) MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) # add the separator varrefs = [SCIP.VarRef(x.value), SCIP.VarRef(y.value)] coefs = [1.0, 1.0] sepa = AddSingleCut.Sepa(inner, varrefs, coefs, 0.0, 0.0) SCIP.include_sepa(inner.scip[], inner.sepas, sepa) # solve the problem SCIP.@SCIP_CALL SCIP.SCIPsolve(inner.scip[]) # SCIP found the non-optimal solution, that remains after the cut. @test MOI.get(optimizer, MOI.TerminationStatus()) == MOI.OPTIMAL @test MOI.get(optimizer, MOI.PrimalStatus()) == MOI.FEASIBLE_POINT @test MOI.get(optimizer, MOI.ObjectiveValue()) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), x) ≈ 0.0 atol = atol rtol = rtol @test MOI.get(optimizer, MOI.VariablePrimal(), y) ≈ 0.0 atol = atol rtol = rtol # free the problem finalize(inner) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
4802
module DummySepa using SCIP """ A minimal no-op separator. """ mutable struct Sepa <: SCIP.AbstractSeparator called::Int64 Sepa() = new(0) end function SCIP.exec_lp(sepa::Sepa) sepa.called += 1 return SCIP.SCIP_DIDNOTRUN end end # module DummySepa module AddSingleCut using SCIP """ A separator, that adds one predefined cut. """ mutable struct Sepa <: SCIP.AbstractSeparator scipd::SCIP.SCIPData varrefs::AbstractArray{SCIP.VarRef} coefs::AbstractArray{Float64} lhs::Float64 rhs::Float64 end function SCIP.exec_lp(sepa::Sepa) SCIP.add_cut_sepa( sepa.scipd.scip[], sepa.scipd.vars, sepa.scipd.sepas, sepa, sepa.varrefs, sepa.coefs, sepa.lhs, sepa.rhs; removable=false, ) return SCIP.SCIP_SEPARATED end end # module AddSingleCut """ sepa_set_scip_parameters(setter::Function) Set all SCIP parameters, that are needed for the sepa-tests using `setter`. # Arguments - `setter(parameter::String, value::Int64)` """ function sepa_set_scip_parameters(setter::Function) setter("display/verblevel", 0) # All the following parameters make sure, that the separator is called and # the cut is added to the LP. setter("presolving/maxrounds", 0) setter("misc/usesymmetry", 0) setter("separating/minefficacy", 0) setter("separating/minefficacyroot", 0) setter("cutselection/hybrid/minortho", 0) setter("cutselection/hybrid/minorthoroot", 0) setter("separating/poolfreq", 1) # These parameters come from `SCIP> set sepa emph off` setter("separating/disjunctive/freq", -1) setter("separating/impliedbounds/freq", -1) setter("separating/gomory/freq", -1) setter("separating/strongcg/freq", -1) setter("separating/aggregation/freq", -1) setter("separating/clique/freq", -1) setter("separating/zerohalf/freq", -1) setter("separating/mcf/freq", -1) setter("separating/flowcover/freq", -1) setter("separating/cmir/freq", -1) setter("separating/rapidlearning/freq", -1) setter("constraints/cardinality/sepafreq", -1) setter("constraints/SOS1/sepafreq", -1) setter("constraints/SOS2/sepafreq", -1) setter("constraints/varbound/sepafreq", -1) setter("constraints/knapsack/sepafreq", -1) setter("constraints/setppc/sepafreq", -1) setter("constraints/linking/sepafreq", -1) setter("constraints/or/sepafreq", -1) setter("constraints/and/sepafreq", -1) setter("constraints/xor/sepafreq", -1) setter("constraints/linear/sepafreq", -1) setter("constraints/orbisack/sepafreq", -1) setter("constraints/symresack/sepafreq", -1) setter("constraints/logicor/sepafreq", -1) setter("constraints/cumulative/sepafreq", -1) setter("constraints/nonlinear/sepafreq", -1) setter("constraints/indicator/sepafreq", -1) # These parameters come from `SCIP> set heuristics off` setter("heuristics/padm/freq", -1) setter("heuristics/ofins/freq", -1) setter("heuristics/trivialnegation/freq", -1) setter("heuristics/reoptsols/freq", -1) setter("heuristics/trivial/freq", -1) setter("heuristics/clique/freq", -1) setter("heuristics/locks/freq", -1) setter("heuristics/vbounds/freq", -1) setter("heuristics/shiftandpropagate/freq", -1) setter("heuristics/completesol/freq", -1) setter("heuristics/simplerounding/freq", -1) setter("heuristics/randrounding/freq", -1) setter("heuristics/zirounding/freq", -1) setter("heuristics/rounding/freq", -1) setter("heuristics/shifting/freq", -1) setter("heuristics/intshifting/freq", -1) setter("heuristics/oneopt/freq", -1) setter("heuristics/indicator/freq", -1) setter("heuristics/adaptivediving/freq", -1) setter("heuristics/farkasdiving/freq", -1) setter("heuristics/feaspump/freq", -1) setter("heuristics/conflictdiving/freq", -1) setter("heuristics/pscostdiving/freq", -1) setter("heuristics/fracdiving/freq", -1) setter("heuristics/nlpdiving/freq", -1) setter("heuristics/veclendiving/freq", -1) setter("heuristics/distributiondiving/freq", -1) setter("heuristics/objpscostdiving/freq", -1) setter("heuristics/rootsoldiving/freq", -1) setter("heuristics/linesearchdiving/freq", -1) setter("heuristics/guideddiving/freq", -1) setter("heuristics/rens/freq", -1) setter("heuristics/alns/freq", -1) setter("heuristics/rins/freq", -1) setter("heuristics/gins/freq", -1) setter("heuristics/lpface/freq", -1) setter("heuristics/crossover/freq", -1) setter("heuristics/undercover/freq", -1) setter("heuristics/subnlp/freq", -1) setter("heuristics/mpec/freq", -1) setter("heuristics/multistart/freq", -1) setter("heuristics/trysol/freq", -1) end
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
code
1711
using MINLPTests, JuMP, SCIP, Test @static if VERSION >= v"1.7" import LinearAlgebra, OpenBLAS32_jll LinearAlgebra.BLAS.lbt_forward(OpenBLAS32_jll.libopenblas_path) end const OPTIMIZER = JuMP.optimizer_with_attributes(SCIP.Optimizer, "display/verblevel" => 0) const OBJTOL = 1e-4 const PRIMALTOL = 1e-3 const DUALTOL = NaN # to disable the query MINLPTests.test_directory( "nlp", OPTIMIZER; objective_tol=OBJTOL, primal_tol=PRIMALTOL, dual_tol=DUALTOL, termination_target=MINLPTests.TERMINATION_TARGET_GLOBAL, primal_target=MINLPTests.PRIMAL_TARGET_GLOBAL, include=["005_010", "007_010"], ) MINLPTests.test_directory( "nlp-cvx", OPTIMIZER; objective_tol=OBJTOL, primal_tol=PRIMALTOL, dual_tol=DUALTOL, termination_target=MINLPTests.TERMINATION_TARGET_GLOBAL, primal_target=MINLPTests.PRIMAL_TARGET_GLOBAL, include=[ "001_010", "002_010", "101_010", "101_012", "102_010", "102_011", "102_012", "103_010", "103_011", "103_012", "103_013", "103_014", "104_010", "105_010", "105_011", "105_012", "105_013", "201_010", "201_011", "202_010", "202_011", "202_012", "202_013", "202_014", "203_010", "204_010", "205_010", ], ) MINLPTests.test_directory( "nlp-mi", OPTIMIZER; objective_tol=OBJTOL, primal_tol=PRIMALTOL, dual_tol=DUALTOL, termination_target=MINLPTests.TERMINATION_TARGET_GLOBAL, primal_target=MINLPTests.PRIMAL_TARGET_GLOBAL, include=["005_010", "007_010", "007_020"], )
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
docs
2921
# News ## v0.10.0 SCIP.jl was upgraded to MathOptInterface `v0.10`. Removed `ManagedSCIP` as a logic layer. Memory management is now done at the `SCIP.Optimizer` layer. ## v0.9.8 Support for SCIP 7.0.2. Automatic SCIP binary installation through [SCIP_jll](https://github.com/JuliaBinaryWrappers/SCIP_jll.jl) built by BinaryBuilder [#177](https://github.com/scipopt/SCIP.jl/pull/177). ## v0.9.7 - support MOI user cut callbacks [#179](https://github.com/SCIP-Interfaces/SCIP.jl/pull/179) ## v0.9.6 - add local CEnum submodule to avoid version conflicts [#175](https://github.com/SCIP-Interfaces/SCIP.jl/pull/175) - support SCIP 7.0.1 [#173](https://github.com/SCIP-Interfaces/SCIP.jl/pull/173) - fix SCIP status bug when adding nonlinear constraints after solving [#171](https://github.com/SCIP-Interfaces/SCIP.jl/pull/171) ## v0.9.5 - implement MOI.DualStatus [#158](https://github.com/SCIP-Interfaces/SCIP.jl/pull/158) ## v0.9.4 - support SCIP 7.0.0 [#149](https://github.com/SCIP-Interfaces/SCIP.jl/pull/149) ## v0.9.3 - add support for VariablePrimalStart [#138](https://github.com/SCIP-Interfaces/SCIP.jl/pull/138) - fix indicator constraints [#137](https://github.com/SCIP-Interfaces/SCIP.jl/pull/137) ## v0.9.2 - support (and require) MOI v0.9.5 [#134](https://github.com/SCIP-Interfaces/SCIP.jl/pull/134) - implement more MOI methods to better support JuMP with `direct_model` [#133](https://github.com/SCIP-Interfaces/SCIP.jl/pull/133) ## v0.9.1 - Add a Julia wrapper for constraint handlers. [#109](https://github.com/SCIP-Interfaces/SCIP.jl/pull/109) ## v0.9.0 - support MOI v0.9 [#126](https://github.com/SCIP-Interfaces/SCIP.jl/pull/126) - SCIP-specific MOI indicator constraint replaced by the new MOI definition [#121](https://github.com/SCIP-Interfaces/SCIP.jl/pull/121) ## v0.8.0 - support Windows [#122](https://github.com/SCIP-Interfaces/SCIP.jl/pull/122) - switch from REQUIRE to Project.toml [#119](https://github.com/SCIP-Interfaces/SCIP.jl/pull/119) ## v0.7.4 - support indicator constraints: [#113](https://github.com/SCIP-Interfaces/SCIP.jl/pull/113) - fix segfaults when accessing solution before solving: [#115](https://github.com/SCIP-Interfaces/SCIP.jl/pull/115) ## v0.7.3 - Support OS X: [#110](https://github.com/SCIP-Interfaces/SCIP.jl/issues/110). ## v0.7.2 - Fix handling of value types when setting parameters: [#15](https://github.com/SCIP-Interfaces/SCIP.jl/issues/15). ## v0.7.1 - Fix translation of coefficients in quadratic constraints: [#106](https://github.com/SCIP-Interfaces/SCIP.jl/issues/106). ## v0.7.0 - Major rewrite with Clang.jl generated wrapper of SCIP headers: [#76](https://github.com/SCIP-Interfaces/SCIP.jl/pull/76). - Add support for MathOptInterface (and JuMP v0.19). - Drop support for MathProgBase. - Drop intermediate layer CSIP between SCIP.jl and SCIP. ## v0.6.1 - Last version to support MathProgBase and JuMP v0.18
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.11.14
3d6a6516d6940a93b732e8ec7127652a0ead89c6
docs
5239
# SCIP.jl [![Build Status](https://github.com/scipopt/SCIP.jl/workflows/CI/badge.svg?branch=master)](https://github.com/scipopt/SCIP.jl/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/scipopt/SCIP.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/scipopt/SCIP.jl) [![Genie Downloads](https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/SCIP)](https://pkgs.genieframework.com?packages=SCIP) [SCIP.jl](https://github.com/scipopt/SCIP.jl) is a Julia interface to the [SCIP](https://scipopt.org) solver. ## Affiliation This wrapper is maintained by the [SCIP project](https://www.scipopt.org/) with the help of the JuMP community. ## License `SCIP.jl` is licensed under the [MIT License](https://github.com/scipopt/SCIP.jl/blob/master/LICENSE). The underlying solver, [scipopt/scip](https://github.com/scipopt/scip), is licensed under the [Apache 2.0 license](https://github.com/scipopt/scip/blob/master/LICENSE). ## Installation Install SCIP.jl using `Pkg.add`: ```julia import Pkg Pkg.add("SCIP") ``` On MacOS and Linux, installing the SCIP Julia package will work out of the box and install the [`SCIP_jll.jl`](https://github.com/JuliaBinaryWrappers/SCIP_jll.jl) and [`SCIP_PaPILO_jll.jl`](https://github.com/JuliaBinaryWrappers/SCIP_PaPILO_jll.jl) dependencies. On Windows, a separate installation of SCIP is still mandatory, as detailed in the "Custom installation" section below. ## Custom installations If you use an older Julia version, Windows, or you want a custom SCIP installation, you must manually install the SCIP binaries. Once installed, set the `SCIPOPTDIR` environment variable to point to the installation path, that is, depending on your operating system, `$SCIPOPTDIR/lib/libscip.so`, `$SCIPOPTDIR/lib/libscip.dylib`, or `$SCIPOPTDIR/bin/scip.dll` must exist. Then, install `SCIP.jl` using `Pkg.add` and `Pkg.build`: ```julia ENV["SCIPOPTDIR"] = "/Users/Oscar/code/SCIP" import Pkg Pkg.add("SCIP") Pkg.build("SCIP") ``` ## Use with JuMP Use SCIP with JuMP as follows: ```julia using JuMP, SCIP model = Model(SCIP.Optimizer) set_attribute(model, "display/verblevel", 0) set_attribute(model, "limits/gap", 0.05) ``` ## Options See the [SCIP documentation](https://scip.zib.de/doc-8.0.0/html/PARAMETERS.php) for a list of supported options. ## MathOptInterface API The SCIP optimizer supports the following constraints and attributes. List of supported objective functions: * [`MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}`](@ref) List of supported variable types: * [`MOI.Reals`](@ref) List of supported constraint types: * [`MOI.ScalarAffineFunction{Float64}`](@ref) in [`MOI.EqualTo{Float64}`](@ref) * [`MOI.ScalarAffineFunction{Float64}`](@ref) in [`MOI.GreaterThan{Float64}`](@ref) * [`MOI.ScalarAffineFunction{Float64}`](@ref) in [`MOI.Interval{Float64}`](@ref) * [`MOI.ScalarAffineFunction{Float64}`](@ref) in [`MOI.LessThan{Float64}`](@ref) * [`MOI.ScalarQuadraticFunction{Float64}`](@ref) in [`MOI.EqualTo{Float64}`](@ref) * [`MOI.ScalarQuadraticFunction{Float64}`](@ref) in [`MOI.GreaterThan{Float64}`](@ref) * [`MOI.ScalarQuadraticFunction{Float64}`](@ref) in [`MOI.Interval{Float64}`](@ref) * [`MOI.ScalarQuadraticFunction{Float64}`](@ref) in [`MOI.LessThan{Float64}`](@ref) * [`MOI.VariableIndex`](@ref) in [`MOI.EqualTo{Float64}`](@ref) * [`MOI.VariableIndex`](@ref) in [`MOI.GreaterThan{Float64}`](@ref) * [`MOI.VariableIndex`](@ref) in [`MOI.Integer`](@ref) * [`MOI.VariableIndex`](@ref) in [`MOI.Interval{Float64}`](@ref) * [`MOI.VariableIndex`](@ref) in [`MOI.LessThan{Float64}`](@ref) * [`MOI.VariableIndex`](@ref) in [`MOI.ZeroOne`](@ref) * [`MOI.VectorOfVariables`](@ref) in [`MOI.SOS1{Float64}`](@ref) * [`MOI.VectorOfVariables`](@ref) in [`MOI.SOS2{Float64}`](@ref) List of supported model attributes: * [`MOI.NLPBlock()`](@ref) * [`MOI.ObjectiveSense()`](@ref) * [`MOI.UserCutCallback()`](@ref) ## Design considerations ### Wrapping the public API All of the public API methods are wrapped and available within the `SCIP` package. This includes the `scip_*.h` and `pub_*.h` headers that are collected in `scip.h`, as well as all default constraint handlers (`cons_*.h`.) The wrapped functions do not transform any data structures and work on the *raw* pointers (for example, `SCIP*` in C, `Ptr{SCIP_}` in Julia). Convenience wrapper functions based on Julia types are added as needed. ### Memory management Programming with SCIP requires dealing with variable and constraint objects that use [reference counting](https://scip.zib.de/doc-8.0.0/html/OBJ.php) for memory management. The `SCIP.Optimizer` wrapper type collects lists of `SCIP_VAR*` and `SCIP_CONS*` under the hood, and it releases all references when it is garbage collected itself (via `finalize`). When adding a variable (`add_variable`) or a constraint (`add_linear_constraint`), an integer index is returned. This index can be used to retrieve the `SCIP_VAR*` or `SCIP_CONS*` pointer via `get_var` and `get_cons` respectively. ### Supported nonlinear operators Supported operators in nonlinear expressions are as follows: * `+` * `-` * `*` * `/` * `^` * `sqrt` * `exp` * `log` * `abs` * `cos` * `sin`
SCIP
https://github.com/scipopt/SCIP.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
603
using Documenter, LsqFit makedocs( format = Documenter.HTML(prettyurls = true, canonical="https://julianlsolvers.github.io/LsqFit.jl/stable/"), sitename = "LsqFit.jl", doctest = false, warnonly = true, pages = Any[ "Home" => "index.md", "Getting Started" => "getting_started.md", "Tutorial" => "tutorial.md", "API References" => "api.md", ], ) deploydocs( repo = "github.com/JuliaNLSolvers/LsqFit.jl.git", target = "build", versions = ["stable" => "v^", "v#.#"], deps = nothing, make = nothing, )
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
591
module LsqFit export curve_fit, margin_error, make_hessian, Avv, # StatsAPI reexports dof, coef, confint, nobs, mse, rss, stderror, weights, residuals, vcov using Distributions using LinearAlgebra using ForwardDiff using Printf using StatsAPI import NLSolversBase: value, value!, jacobian, jacobian!, value_jacobian!!, OnceDifferentiable using StatsAPI: coef, confint, dof, nobs, rss, stderror, weights, residuals, vcov import Base.summary include("geodesic.jl") include("levenberg_marquardt.jl") include("curve_fit.jl") end
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
10061
struct LsqFitResult{P,R,J,W <: AbstractArray,T} param::P resid::R jacobian::J converged::Bool trace::T wt::W end StatsAPI.coef(lfr::LsqFitResult) = lfr.param StatsAPI.dof(lfr::LsqFitResult) = nobs(lfr) - length(coef(lfr)) StatsAPI.nobs(lfr::LsqFitResult) = length(lfr.resid) StatsAPI.rss(lfr::LsqFitResult) = sum(abs2, lfr.resid) StatsAPI.weights(lfr::LsqFitResult) = lfr.wt StatsAPI.residuals(lfr::LsqFitResult) = lfr.resid mse(lfr::LsqFitResult) = rss(lfr) / dof(lfr) isconverged(lsr::LsqFitResult) = lsr.converged function check_data_health(xdata, ydata) if any(ismissing, xdata) || any(ismissing, ydata) error("Data contains `missing` values and a fit cannot be performed") end if any(isinf, xdata) || any(isinf, ydata) || any(isnan, xdata) || any(isnan, ydata) error("Data contains `Inf` or `NaN` values and a fit cannot be performed") end end # provide a method for those who have their own Jacobian function function lmfit(f, g, p0::AbstractArray, wt::AbstractArray; kwargs...) r = f(p0) R = OnceDifferentiable(f, g, p0, copy(r); inplace=false) lmfit(R, p0, wt; kwargs...) end # for inplace f and inplace g function lmfit(f!, g!, p0::AbstractArray, wt::AbstractArray, r::AbstractArray; kwargs...) R = OnceDifferentiable(f!, g!, p0, copy(r); inplace=true) lmfit(R, p0, wt; kwargs...) end # for inplace f only function lmfit( f, p0::AbstractArray, wt::AbstractArray, r::AbstractArray; autodiff=:finite, kwargs..., ) R = OnceDifferentiable(f, p0, copy(r); inplace=true, autodiff=autodiff) lmfit(R, p0, wt; kwargs...) end function lmfit(f, p0::AbstractArray, wt::AbstractArray; autodiff=:finite, kwargs...) # this is a convenience function for the curve_fit() methods # which assume f(p) is the cost functionj i.e. the residual of a # model where # model(xpts, params...) = ydata + error (noise) # this minimizes f(p) using a least squares sum of squared error: # rss = sum(f(p)^2) # # returns p, f(p), g(p) where # p : best fit parameters # f(p) : function evaluated at best fit p, (weighted) residuals # g(p) : estimated Jacobian at p (Jacobian with respect to p) # construct Jacobian function, which uses finite difference method r = f(p0) autodiff = autodiff == :forwarddiff ? :forward : autodiff R = OnceDifferentiable(f, p0, copy(r); inplace=false, autodiff=autodiff) lmfit(R, p0, wt; kwargs...) end function lmfit( R::OnceDifferentiable, p0::AbstractArray, wt::AbstractArray; autodiff=:finite, kwargs..., ) results = levenberg_marquardt(R, p0; kwargs...) p = results.minimizer converged = isconverged(results) return LsqFitResult(p, value!(R, p), jacobian!(R, p), converged, results.trace, wt) end """ curve_fit(model, xdata, ydata, p0) -> fit curve_fit(model, xdata, ydata, wt, p0) -> fit Fit data to a non-linear `model`. `p0` is an initial model parameter guess (see Example), and `wt` is an optional array of weights. The return object is a composite type (`LsqFitResult`), with some interesting values: * `fit.resid` : residuals = vector of residuals * `fit.jacobian` : estimated Jacobian at solution additionally, it is possible to query the degrees of freedom with * `dof(fit)` * `coef(fit)` ## Example ```julia # a two-parameter exponential model # x: array of independent variables # p: array of model parameters model(x, p) = p[1]*exp.(-x.*p[2]) # some example data # xdata: independent variables # ydata: dependent variable xdata = range(0, stop=10, length=20) ydata = model(xdata, [1.0 2.0]) + 0.01*randn(length(xdata)) p0 = [0.5, 0.5] fit = curve_fit(model, xdata, ydata, p0) ``` """ function curve_fit end function curve_fit( model, xdata::AbstractArray, ydata::AbstractArray, p0::AbstractArray; inplace=false, kwargs..., ) check_data_health(xdata, ydata) # construct the cost function T = eltype(ydata) if inplace f! = (F, p) -> (model(F, xdata, p); @. F = F - ydata) lmfit(f!, p0, T[], ydata; kwargs...) else f = (p) -> model(xdata, p) - ydata lmfit(f, p0, T[]; kwargs...) end end function curve_fit( model, jacobian_model, xdata::AbstractArray, ydata::AbstractArray, p0::AbstractArray; inplace=false, kwargs..., ) check_data_health(xdata, ydata) T = eltype(ydata) if inplace f! = (F, p) -> (model(F, xdata, p); @. F = F - ydata) g! = (G, p) -> jacobian_model(G, xdata, p) lmfit(f!, g!, p0, T[], copy(ydata); kwargs...) else f = (p) -> model(xdata, p) - ydata g = (p) -> jacobian_model(xdata, p) lmfit(f, g, p0, T[]; kwargs...) end end function curve_fit( model, xdata::AbstractArray, ydata::AbstractArray, wt::AbstractArray, p0::AbstractArray; inplace=false, kwargs..., ) check_data_health(xdata, ydata) # construct a weighted cost function, with a vector weight for each ydata # for example, this might be wt = 1/sigma where sigma is some error term u = sqrt.(wt) # to be consistant with the matrix form if inplace f! = (F, p) -> (model(F, xdata, p); @. F = u * (F - ydata)) lmfit(f!, p0, wt, ydata; kwargs...) else f = (p) -> u .* (model(xdata, p) - ydata) lmfit(f, p0, wt; kwargs...) end end function curve_fit( model, jacobian_model, xdata::AbstractArray, ydata::AbstractArray, wt::AbstractArray, p0::AbstractArray; inplace=false, kwargs..., ) check_data_health(xdata, ydata) u = sqrt.(wt) # to be consistant with the matrix form if inplace f! = (F, p) -> (model(F, xdata, p); @. F = u * (F - ydata)) g! = (G, p) -> (jacobian_model(G, xdata, p); @. G = u * G) lmfit(f!, g!, p0, wt, ydata; kwargs...) else f = (p) -> u .* (model(xdata, p) - ydata) g = (p) -> u .* (jacobian_model(xdata, p)) lmfit(f, g, p0, wt; kwargs...) end end function curve_fit( model, xdata::AbstractArray, ydata::AbstractArray, wt::AbstractMatrix, p0::AbstractArray; kwargs..., ) check_data_health(xdata, ydata) # as before, construct a weighted cost function with where this # method uses a matrix weight. # for example: an inverse_covariance matrix # Cholesky is effectively a sqrt of a matrix, which is what we want # to minimize in the least-squares of levenberg_marquardt() # This requires the matrix to be positive definite u = cholesky(wt).U f(p) = u * (model(xdata, p) - ydata) lmfit(f, p0, wt; kwargs...) end function curve_fit( model, jacobian_model, xdata::AbstractArray, ydata::AbstractArray, wt::AbstractMatrix, p0::AbstractArray; kwargs..., ) check_data_health(xdata, ydata) u = cholesky(wt).U f(p) = u * (model(xdata, p) - ydata) g(p) = u * (jacobian_model(xdata, p)) lmfit(f, g, p0, wt; kwargs...) end function StatsAPI.vcov(fit::LsqFitResult) # computes covariance matrix of fit parameters J = fit.jacobian if isempty(fit.wt) r = fit.resid # compute the covariance matrix from the QR decomposition Q, R = qr(J) Rinv = inv(R) covar = Rinv * Rinv' * mse(fit) else covar = inv(J' * J) end return covar end function StatsAPI.stderror(fit::LsqFitResult; rtol::Real=NaN, atol::Real=0) # computes standard error of estimates from # fit : a LsqFitResult from a curve_fit() # atol : absolute tolerance for approximate comparisson to 0.0 in negativity check # rtol : relative tolerance for approximate comparisson to 0.0 in negativity check covar = vcov(fit) # then the standard errors are given by the sqrt of the diagonal vars = diag(covar) vratio = minimum(vars) / maximum(vars) if !isapprox( vratio, 0.0, atol=atol, rtol=isnan(rtol) ? Base.rtoldefault(vratio, 0.0, 0) : rtol, ) && vratio < 0.0 error("Covariance matrix is negative for atol=$atol and rtol=$rtol") end return sqrt.(abs.(vars)) end function margin_error(fit::LsqFitResult, alpha=0.05; rtol::Real=NaN, atol::Real=0) # computes margin of error at alpha significance level from # fit : a LsqFitResult from a curve_fit() # alpha : significance level, e.g. alpha=0.05 for 95% confidence # atol : absolute tolerance for approximate comparisson to 0.0 in negativity check # rtol : relative tolerance for approximate comparisson to 0.0 in negativity check std_errors = stderror(fit; rtol=rtol, atol=atol) dist = TDist(dof(fit)) critical_values = eltype(coef(fit))(quantile(dist, Float64(1 - alpha / 2))) # scale standard errors by quantile of the student-t distribution (critical values) return std_errors * critical_values end function StatsAPI.confint(fit::LsqFitResult; level=0.95, rtol::Real=NaN, atol::Real=0) # computes confidence intervals at alpha significance level from # fit : a LsqFitResult from a curve_fit() # level : confidence level # atol : absolute tolerance for approximate comparisson to 0.0 in negativity check # rtol : relative tolerance for approximate comparisson to 0.0 in negativity check std_errors = stderror(fit; rtol=rtol, atol=atol) margin_of_errors = margin_error(fit, 1 - level; rtol=rtol, atol=atol) return collect(zip(coef(fit) - margin_of_errors, coef(fit) + margin_of_errors)) end @deprecate(confidence_interval(fit::LsqFitResult, alpha=0.05; rtol::Real=NaN, atol::Real=0), confint(fit; level=(1 - alpha), rtol=rtol, atol=atol)) @deprecate estimate_covar(fit::LsqFitResult) vcov(fit) @deprecate standard_errors(args...; kwargs...) stderror(args...; kwargs...) @deprecate estimate_errors( fit::LsqFitResult, confidence=0.95; rtol::Real=NaN, atol::Real=0, ) margin_error(fit, 1 - confidence; rtol=rtol, atol=atol)
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
1989
# see related https://discourse.julialang.org/t/nested-forwarddiff-jacobian-calls-with-inplace-function/21232/7 function make_out_of_place_func(f!, x, make_buffer) y = make_buffer(f!, x) # make_buffer overloads will be defined below x -> f!(y, x) end struct OutOfPlace{F,D} f!::F out_of_place_funcs::Dict{Type,D} make_buffer::D function OutOfPlace(f!::T, dict::Dict{Type,D}, shape::Tuple) where {T,D} mk(::T, p) = similar(p, shape) new{T,D}(f!, dict, mk) end end OutOfPlace(f!, shape) = OutOfPlace(f!, Dict{Type,Function}(), shape) #no sure how to remove the `Function` here eval_f(f::F, x) where {F} = f(x) # function barrier function (oop::OutOfPlace{F})(x) where {F} T = eltype(x) f = get!( () -> make_out_of_place_func(oop.f!, x, oop.make_buffer), oop.out_of_place_funcs, T, ) eval_f(f, x) end function make_hessian(f!, x0, p0) f = OutOfPlace(f!, (length(x0),)) g! = (outjac, p) -> (ForwardDiff.jacobian!(outjac, f, p); outjac = outjac') g = OutOfPlace(g!, (length(x0), length(p0))) h! = (outjac2, p) -> (ForwardDiff.jacobian!(outjac2, g, p); reshape(outjac2', length(p0), length(p0), length(x0))) h! end struct Avv h!::Function hessians::Array{Float64} function Avv(h!::Function, n::Int, m::Int) hessians = Array{Float64}(undef, m * n, n) new(h!, hessians) end end function (avv::Avv)(dir_deriv::AbstractVector, p::AbstractVector, v::AbstractVector) hess = avv.h!(avv.hessians, p) #half of the runtime vHv!(dir_deriv, hess, v) #half of the runtime, almost all the memory end function vHv!(dir_deriv::AbstractVector, hessians::AbstractArray, v::AbstractVector) tmp = similar(v) #v shouldn't be too large in general, so I kept it here vt = v' for i = 1:length(dir_deriv) @views mul!(tmp, hessians[:, :, i], v) #this line is particularly expensive memory-wise dir_deriv[i] = vt * tmp end end
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
10533
struct LMState{T} iteration::Int value::Float64 g_norm::Float64 metadata::Dict end function Base.show(io::IO, t::LMState) @printf io "%6d %14e %14e\n" t.iteration t.value t.g_norm if !isempty(t.metadata) for (key, value) in t.metadata @printf io " * %s: %s\n" key value end end return end LMTrace{T} = Vector{LMState{T}} function Base.show(io::IO, tr::LMTrace) @printf io "Iter Function value Gradient norm \n" @printf io "------ -------------- --------------\n" for state in tr show(io, state) end return end struct LMResults{O,T,Tval,N} method::O initial_x::Array{T,N} minimizer::Array{T,N} minimum::Tval iterations::Int iteration_converged::Bool x_converged::Bool g_converged::Bool g_tol::Tval trace::LMTrace{O} f_calls::Int g_calls::Int end minimizer(lsr::LMResults) = lsr.minimizer isconverged(lsr::LMResults) = lsr.x_converged || lsr.g_converged struct LevenbergMarquardt end Base.summary(::LevenbergMarquardt) = "Levenberg-Marquardt" """ `levenberg_marquardt(f, g, initial_x; <keyword arguments>` Returns the argmin over x of `sum(f(x).^2)` using the Levenberg-Marquardt algorithm, and an estimate of the Jacobian of `f` at x. The function `f` should take an input vector of length n and return an output vector of length m. The function `g` is the Jacobian of f, and should return an m x n matrix. `initial_x` is an initial guess for the solution. Implements box constraints as described in Kanzow, Yamashita, Fukushima (2004; J Comp & Applied Math). # Keyword arguments * `x_tol::Real=1e-8`: search tolerance in x * `g_tol::Real=1e-12`: search tolerance in gradient * `maxIter::Integer=1000`: maximum number of iterations * `min_step_quality=1e-3`: for steps below this quality, the trust region is shrinked * `good_step_quality=0.75`: for steps above this quality, the trust region is expanded * `lambda::Real=10`: (inverse of) initial trust region radius * `tau=Inf`: set initial trust region radius using the heuristic : tau*maximum(jacobian(df)'*jacobian(df)) * `lambda_increase=10.0`: `lambda` is multiplied by this factor after step below min quality * `lambda_decrease=0.1`: `lambda` is multiplied by this factor after good quality steps * `show_trace::Bool=false`: print a status summary on each iteration if true * `lower,upper=[]`: bound solution to these limits """ # I think a smarter way to do this *might* be to create a type similar to `OnceDifferentiable` # and the like. This way we could not only merge the two functions, but also have a convenient # way to provide an autodiff-made acceleration when someone doesn't provide an `avv`. # it would probably be very inefficient performace-wise for most cases, but it wouldn't hurt to have it somewhere function levenberg_marquardt( df::OnceDifferentiable, initial_x::AbstractVector{T}; x_tol::Real=1e-8, g_tol::Real=1e-12, maxIter::Integer=1000, maxTime::Float64=Inf, lambda=T(10), tau=T(Inf), lambda_increase::Real=10.0, lambda_decrease::Real=0.1, min_step_quality::Real=1e-3, good_step_quality::Real=0.75, show_trace::Bool=false, store_trace::Bool=false, lower::AbstractVector{T}=Array{T}(undef, 0), upper::AbstractVector{T}=Array{T}(undef, 0), avv!::Union{Function,Nothing,Avv}=nothing, ) where {T} # First evaluation value_jacobian!!(df, initial_x) if isfinite(tau) lambda = tau * maximum(jacobian(df)' * jacobian(df)) end # check parameters ( (isempty(lower) || length(lower) == length(initial_x)) && (isempty(upper) || length(upper) == length(initial_x)) ) || throw( ArgumentError( "Bounds must either be empty or of the same length as the number of parameters.", ), ) ( (isempty(lower) || all(initial_x .>= lower)) && (isempty(upper) || all(initial_x .<= upper)) ) || throw(ArgumentError("Initial guess must be within bounds.")) (0 <= min_step_quality < 1) || throw(ArgumentError(" 0 <= min_step_quality < 1 must hold.")) (0 < good_step_quality <= 1) || throw(ArgumentError(" 0 < good_step_quality <= 1 must hold.")) (min_step_quality < good_step_quality) || throw(ArgumentError("min_step_quality < good_step_quality must hold.")) # other constants MAX_LAMBDA = 1e16 # minimum trust region radius MIN_LAMBDA = 1e-16 # maximum trust region radius MIN_DIAGONAL = 1e-6 # lower bound on values of diagonal matrix used to regularize the trust region step converged = false x_converged = false g_converged = false iterCt = 0 x = copy(initial_x) delta_x = copy(initial_x) a = similar(x) trial_f = similar(value(df)) residual = sum(abs2, value(df)) Tval = typeof(residual) # Create buffers n = length(x) m = length(value(df)) JJ = Matrix{T}(undef, n, n) n_buffer = Vector{T}(undef, n) Jdelta_buffer = similar(value(df)) # and an alias for the jacobian J = jacobian(df) dir_deriv = Array{T}(undef, m) v = Array{T}(undef, n) # Maintain a trace of the system. tr = LMTrace{LevenbergMarquardt}() if show_trace || store_trace d = Dict("lambda" => lambda) os = LMState{LevenbergMarquardt}(iterCt, sum(abs2, value(df)), NaN, d) push!(tr, os) if show_trace println(os) end end startTime = time() while (~converged && iterCt < maxIter && maxTime > time() - startTime) # jacobian! will check if x is new or not, so it is only actually # evaluated if x was updated last iteration. jacobian!(df, x) # has alias J # we want to solve: # argmin 0.5*||J(x)*delta_x + f(x)||^2 + lambda*||diagm(J'*J)*delta_x||^2 # Solving for the minimum gives: # (J'*J + lambda*diagm(DtD)) * delta_x == -J' * f(x), where DtD = sum(abs2, J,1) # Where we have used the equivalence: diagm(J'*J) = diagm(sum(abs2, J,1)) # It is additionally useful to bound the elements of DtD below to help # prevent "parameter evaporation". DtD = vec(sum(abs2, J, dims=1)) for i = 1:length(DtD) if DtD[i] <= MIN_DIAGONAL DtD[i] = MIN_DIAGONAL end end # delta_x = ( J'*J + lambda * Diagonal(DtD) ) \ ( -J'*value(df) ) mul!(JJ, transpose(J), J) @simd for i = 1:n @inbounds JJ[i, i] += lambda * DtD[i] end # n_buffer is delta C, JJ is g compared to Mark's code mul!(n_buffer, transpose(J), value(df)) rmul!(n_buffer, -1) v .= JJ \ n_buffer if avv! != nothing # GEODESIC ACCELERATION PART avv!(dir_deriv, x, v) mul!(a, transpose(J), dir_deriv) rmul!(a, -1) # we multiply by -1 before the decomposition/division LAPACK.potrf!('U', JJ) # in place cholesky decomposition LAPACK.potrs!('U', JJ, a) # divides a by JJ, taking into account the fact that JJ is now the `U` cholesky decoposition of what it was before rmul!(a, 0.5) delta_x .= v .+ a # end of the GEODESIC ACCELERATION PART else delta_x = v end # apply box constraints if !isempty(lower) @simd for i = 1:n @inbounds delta_x[i] = max(x[i] + delta_x[i], lower[i]) - x[i] end end if !isempty(upper) @simd for i = 1:n @inbounds delta_x[i] = min(x[i] + delta_x[i], upper[i]) - x[i] end end # if the linear assumption is valid, our new residual should be: mul!(Jdelta_buffer, J, delta_x) Jdelta_buffer .= Jdelta_buffer .+ value(df) predicted_residual = sum(abs2, Jdelta_buffer) # try the step and compute its quality # compute it inplace according to NLSolversBase value(obj, cache, state) # interface. No bang (!) because it doesn't update df besides mutating # the number of f_calls # re-use n_buffer n_buffer .= x .+ delta_x value(df, trial_f, n_buffer) # update the sum of squares trial_residual = sum(abs2, trial_f) # step quality = residual change / predicted residual change rho = (trial_residual - residual) / (predicted_residual - residual) if trial_residual < residual && rho > min_step_quality # apply the step to x - n_buffer is ready to be used by the delta_x # calculations after this step. x .= n_buffer # There should be an update_x_value to do this safely copyto!(df.x_f, x) copyto!(value(df), trial_f) residual = trial_residual if rho > good_step_quality # increase trust region radius lambda = max(lambda_decrease * lambda, MIN_LAMBDA) end else # decrease trust region radius lambda = min(lambda_increase * lambda, MAX_LAMBDA) end iterCt += 1 # show state if show_trace || store_trace g_norm = norm(J' * value(df), Inf) d = Dict("g(x)" => g_norm, "dx" => copy(delta_x), "lambda" => lambda) os = LMState{LevenbergMarquardt}(iterCt, sum(abs2, value(df)), g_norm, d) push!(tr, os) if show_trace println(os) end end # check convergence criteria: # 1. Small gradient: norm(J^T * value(df), Inf) < g_tol # 2. Small step size: norm(delta_x) < x_tol if norm(J' * value(df), Inf) < g_tol g_converged = true end if norm(delta_x) < x_tol * (x_tol + norm(x)) x_converged = true end converged = g_converged | x_converged end LMResults( LevenbergMarquardt(), # method initial_x, # initial_x x, # minimizer sum(abs2, value(df)), # minimum iterCt, # iterations !converged, # iteration_converged x_converged, # x_converged g_converged, # g_converged Tval(g_tol), # g_tol tr, # trace first(df.f_calls), # f_calls first(df.df_calls), # g_calls ) end
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
4358
using LsqFit, Test, StableRNGs, LinearAlgebra @testset "curve fit" begin # before testing the model, check whether missing/null data is rejected tdata = [rand(1:10, 5)..., missing] @test_throws ErrorException( "Data contains `missing` values and a fit cannot be performed", ) LsqFit.check_data_health(tdata, tdata) tdata = [rand(1:10, 5)..., Inf] @test_throws ErrorException( "Data contains `Inf` or `NaN` values and a fit cannot be performed", ) LsqFit.check_data_health(tdata, tdata) tdata = [rand(1:10, 5)..., NaN] @test_throws ErrorException( "Data contains `Inf` or `NaN` values and a fit cannot be performed", ) LsqFit.check_data_health(tdata, tdata) for T in (Float64, BigFloat) # fitting noisy data to an exponential model # TODO: Change to `.-x` when 0.5 support is dropped model(x, p) = p[1] .* exp.(-x .* p[2]) # some example data rng = StableRNG(125) xdata = range(0, stop = 10, length = 20) ydata = T.(model(xdata, [1.0, 2.0]) + 0.01 * randn(rng, length(xdata))) p0 = T.([0.5, 0.5]) for ad in (:finite, :forward, :forwarddiff) fit = curve_fit(model, xdata, ydata, p0; autodiff = ad) @test norm(fit.param - [1.0, 2.0]) < 0.05 @test fit.converged # can also get error estimates on the fit parameters errors = margin_error(fit, 0.05) @test norm(errors - [0.025, 0.11]) < 0.01 end # if your model is differentiable, it can be faster and/or more accurate # to supply your own jacobian instead of using the finite difference function jacobian_model(x, p) J = Array{Float64}(undef, length(x), length(p)) J[:, 1] = exp.(-x .* p[2]) #dmodel/dp[1] J[:, 2] = -x .* p[1] .* J[:, 1] #dmodel/dp[2] J end jacobian_fit = curve_fit(model, jacobian_model, xdata, ydata, p0;show_trace=true) @test norm(jacobian_fit.param - [1.0, 2.0]) < 0.05 @test jacobian_fit.converged @testset "#195" begin @test length(jacobian_fit.trace) > 1 @test jacobian_fit.trace[end].metadata["dx"][1] != jacobian_fit.trace[end-1].metadata["dx"][1] end # some example data yvars = T.(1e-6 * rand(rng, length(xdata))) ydata = T.(model(xdata, [1.0, 2.0]) + sqrt.(yvars) .* randn(rng, length(xdata))) fit = curve_fit(model, xdata, ydata, 1 ./ yvars, T.([0.5, 0.5])) @test norm(fit.param - [1.0, 2.0]) < 0.05 @test fit.converged # test matrix valued weights ( #161 ) weights = LinearAlgebra.diagm(1 ./ yvars) fit_matrixweights = curve_fit(model, xdata, ydata, weights, T.([0.5, 0.5])) @test fit.param == fit_matrixweights.param # can also get error estimates on the fit parameters errors = margin_error(fit, T(0.1)) @test norm(errors - [0.017, 0.075]) < 0.1 # test with user-supplied jacobian and weights fit = curve_fit(model, jacobian_model, xdata, ydata, 1 ./ yvars, p0) println("norm(fit.param - [1.0, 2.0]) < 0.05 ? ", norm(fit.param - [1.0, 2.0])) @test norm(fit.param - [1.0, 2.0]) < 0.05 @test fit.converged # Parameters can also be inferred using arbitrary precision fit = curve_fit( model, xdata, ydata, 1 ./ yvars, BigFloat.(p0); x_tol = T(1e-20), g_tol = T(1e-20), ) @test fit.converged fit = curve_fit( model, jacobian_model, xdata, ydata, 1 ./ yvars, BigFloat.(p0); x_tol = T(1e-20), g_tol = T(1e-20), ) @test fit.converged curve_fit(model, jacobian_model, xdata, ydata, 1 ./ yvars, [0.5, 0.5]; tau = 0.0001) end end @testset "#167" begin x = collect(1:10) y = copy(x) @. model(x, p) = p[1] * x + p[2] p0 = [0.0, -5.0] fit = curve_fit(model, x, y, p0) # no bounds fit_bounded = curve_fit(model, x, y, p0; upper = [+Inf, -5.0]) # with bounds @test coef(fit)[1] < coef(fit_bounded)[1] @test coef(fit)[1] ≈ 1 @test coef(fit_bounded)[1] ≈ 1.22727271 end
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
5689
using LsqFit, Test, StableRNGs, LinearAlgebra @testset "inplace" begin # fitting noisy data to an exponential model # TODO: Change to `.-x` when 0.5 support is dropped @. model(x, p) = p[1] * exp(-x * p[2]) model_inplace(F, x, p) = (@. F = p[1] * exp(-x * p[2])) # some example data rng = StableRNG(123) xdata = range(0, stop = 10, length = 500000) ydata = model(xdata, [1.0, 2.0]) + 0.01 * randn(rng, length(xdata)) p0 = [0.5, 0.5] # if your model is differentiable, it can be faster and/or more accurate # to supply your own jacobian instead of using the finite difference function jacobian_model(x, p) J = Array{Float64}(undef, length(x), length(p)) @. J[:, 1] = exp(-x * p[2]) #dmodel/dp[1] @. @views J[:, 2] = -x * p[1] * J[:, 1] J end function jacobian_model_inplace(J::Array{Float64,2}, x, p) @. J[:, 1] = exp(-x * p[2]) #dmodel/dp[1] @. @views J[:, 2] = -x * p[1] * J[:, 1] end f(p) = model(xdata, p) - ydata g(p) = jacobian_model(xdata, p) df = OnceDifferentiable(f, g, p0, similar(ydata); inplace = false) evalf(x) = NLSolversBase.value!!(df, x) evalg(x) = NLSolversBase.jacobian!!(df, x) r = evalf(p0) j = evalg(p0) f_inplace = (F, p) -> (model_inplace(F, xdata, p); @. F = F - ydata) g_inplace = (G, p) -> jacobian_model_inplace(G, xdata, p) df_inplace = OnceDifferentiable(f_inplace, g_inplace, p0, similar(ydata); inplace = true) evalf_inplace(x) = NLSolversBase.value!!(df_inplace, x) evalg_inplace(x) = NLSolversBase.jacobian!!(df_inplace, x) r_inplace = evalf_inplace(p0) j_inplace = evalg_inplace(p0) @test r == r_inplace @test j == j_inplace println("--------------\nPerformance of non-inplace") println("\t Evaluation function") stop = 8 #8 because the tests afterwards will call the eval function 8 or 9 times, so it makes it easy to compare step = 1 @time for i in range(0, stop = stop, step = step) evalf(p0) end println("\t Jacobian function") @time for i in range(0, stop = stop, step = step) evalg(p0) end println("--------------\nPerformance of inplace") println("\t Evaluation function") @time for i in range(0, stop = stop, step = step) evalf_inplace(p0) end println("\t Jacobian function") @time for i in range(0, stop = stop, step = step) evalg_inplace(p0) end curve_fit(model, xdata, ydata, p0; maxIter = 100) #warmup curve_fit(model_inplace, xdata, ydata, p0; inplace = true, maxIter = 100) #explicit jac curve_fit(model, jacobian_model, xdata, ydata, p0; maxIter = 100) curve_fit( model_inplace, jacobian_model_inplace, xdata, ydata, p0; inplace = true, maxIter = 100, ) println("--------------\nPerformance of curve_fit") println("\t Non-inplace") fit = @time curve_fit(model, xdata, ydata, p0; maxIter = 100) @test fit.converged println("\t Inplace") fit_inplace = @time curve_fit(model_inplace, xdata, ydata, p0; inplace = true, maxIter = 100) @test fit_inplace.converged @test fit_inplace.param == fit.param println("\t Non-inplace with jacobian") fit_jac = @time curve_fit(model, jacobian_model, xdata, ydata, p0; maxIter = 100) @test fit_jac.converged println("\t Inplace with jacobian") fit_inplace_jac = @time curve_fit( model_inplace, jacobian_model_inplace, xdata, ydata, p0; inplace = true, maxIter = 100, ) @test fit_inplace_jac.converged @test fit_jac.param == fit_inplace_jac.param # some example data yvars = 1e-6 * rand(rng, length(xdata)) ydata = model(xdata, [1.0, 2.0]) + sqrt.(yvars) .* randn(rng, length(xdata)) println("--------------\nPerformance of curve_fit with weights") curve_fit(model, xdata, ydata, 1 ./ yvars, [0.5, 0.5]) curve_fit( model_inplace, xdata, ydata, 1 ./ yvars, [0.5, 0.5]; inplace = true, maxIter = 100, ) curve_fit(model, jacobian_model, xdata, ydata, 1 ./ yvars, [0.5, 0.5]) curve_fit( model_inplace, jacobian_model_inplace, xdata, ydata, 1 ./ yvars, [0.5, 0.5]; inplace = true, maxIter = 100, ) println("\t Non-inplace with weights") fit_wt = @time curve_fit( model, jacobian_model, xdata, ydata, 1 ./ yvars, [0.5, 0.5]; maxIter = 100, ) @test fit_wt.converged println("\t Inplace with weights") fit_inplace_wt = @time curve_fit( model_inplace, xdata, ydata, 1 ./ yvars, [0.5, 0.5]; inplace = true, maxIter = 100, ) @test fit_inplace_wt.converged @test maximum(abs.(fit_wt.param - fit_inplace_wt.param)) < 1e-15 println("\t Non-inplace with jacobian with weights") fit_wt_jac = @time curve_fit( model, jacobian_model, xdata, ydata, 1 ./ yvars, [0.5, 0.5]; maxIter = 100, ) @test fit_wt_jac.converged println("\t Inplace with jacobian with weights") fit_inplace_wt_jac = @time curve_fit( model_inplace, jacobian_model_inplace, xdata, ydata, 1 ./ yvars, [0.5, 0.5]; inplace = true, maxIter = 100, ) @test fit_inplace_wt_jac.converged @test maximum(abs.(fit_wt_jac.param - fit_inplace_wt_jac.param)) < 1e-15 end
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
5050
using LsqFit, Test, StableRNGs @testset "geodesic" begin # fitting noisy data to an exponential model model(x, p) = @. p[1] * exp(-x * p[2]) #model(x,p) = [p[1],100*(p[2]-p[1]^2)] # some example data rng = StableRNG(345) xdata = range(0, stop = 10, length = 50_000) ydata = model(xdata, [1.0, 2.0]) + 0.01 * randn(rng, length(xdata)) p0 = [0.5, 0.5] function jacobian_model(x, p) J = Array{Float64}(undef, length(x), length(p)) @. J[:, 1] = exp(-x * p[2]) #dmodel/dp[1] @. @views J[:, 2] = -x * p[1] * J[:, 1] J end #Generating the "automatic" avv model_inplace(out, p) = @. out = p[1] * exp(-xdata * p[2]) hessians = Array{Float64}(undef, length(xdata) * length(p0), length(p0)) h! = make_hessian(model_inplace, xdata, p0) auto_avv! = Avv(h!, length(p0), length(xdata)) # a couple notes on the Avv function: # - the basic idea is to see the model output as simply a collection of functions: f1...fm # - then Avv return an array of size m, where each elements corresponds to # v'H(p)v, with H an n*n Hessian matrix of the m-th function, with n the size of p function manual_avv!(dir_deriv, p, v) v1 = v[1] v2 = v[2] for i = 1:length(xdata) #compute all the elements of the H matrix h11 = 0 h12 = (-xdata[i] * exp(-xdata[i] * p[2])) #h21 = h12 h22 = (xdata[i]^2 * p[1] * exp(-xdata[i] * p[2])) # manually compute v'Hv. This whole process might seem cumbersome, but # allocating temporary matrices quickly becomes REALLY expensive and might even # render the use of geodesic acceleration terribly inefficient dir_deriv[i] = h11 * v1^2 + 2 * h12 * v1 * v2 + h22 * v2^2 end end curve_fit(model, jacobian_model, xdata, ydata, p0; maxIter = 1) #warmup curve_fit( model, jacobian_model, xdata, ydata, p0; maxIter = 1, avv! = manual_avv!, lambda = 0, min_step_quality = 0, ) #lambda = 0 to match Mark's code curve_fit( model, jacobian_model, xdata, ydata, p0; maxIter = 10, avv! = auto_avv!, lambda = 0, min_step_quality = 0, ) println("--------------\nPerformance of curve_fit vs geo") println("\t Non-inplace") fit = @time curve_fit(model, jacobian_model, xdata, ydata, p0; maxIter = 1000) @test fit.converged println("\t Geodesic") fit_geo = @time curve_fit( model, jacobian_model, xdata, ydata, p0; maxIter = 10, avv! = manual_avv!, lambda = 0, min_step_quality = 0, ) @test fit_geo.converged println("\t Geodesic - auto avv!") fit_geo_auto = @time curve_fit( model, jacobian_model, xdata, ydata, p0; maxIter = 10, avv! = auto_avv!, lambda = 0, min_step_quality = 0, ) @test fit_geo_auto.converged @test maximum(abs.(fit.param - [1.0, 2.0])) < 1e-1 @test maximum(abs.(fit.param - fit_geo.param)) < 1e-6 @test maximum(abs.(fit.param - fit_geo_auto.param)) < 1e-6 #with noise yvars = 1e-6 * rand(rng, length(xdata)) ydata = model(xdata, [1.0, 2.0]) + sqrt.(yvars) .* randn(rng, length(xdata)) #warm up curve_fit(model, jacobian_model, xdata, ydata, 1 ./ yvars, p0; maxIter = 1) curve_fit( model, jacobian_model, xdata, ydata, 1 ./ yvars, p0; maxIter = 1, avv! = manual_avv!, lambda = 0, min_step_quality = 0, ) curve_fit( model, jacobian_model, xdata, ydata, 1 ./ yvars, p0; maxIter = 1, avv! = auto_avv!, lambda = 0, min_step_quality = 0, ) println("--------------\nPerformance of curve_fit vs geo with weights") println("\t Non-inplace") fit_wt = @time curve_fit(model, jacobian_model, xdata, ydata, 1 ./ yvars, p0; maxIter = 100) @test fit_wt.converged println("\t Geodesic") fit_geo_wt = @time curve_fit( model, jacobian_model, xdata, ydata, 1 ./ yvars, p0; maxIter = 100, avv! = manual_avv!, lambda = 0, min_step_quality = 0, ) @test fit_geo_wt.converged println("\t Geodesic - auto avv!") fit_geo_auto_wt = @time curve_fit( model, jacobian_model, xdata, ydata, 1 ./ yvars, p0; maxIter = 100, avv! = auto_avv!, lambda = 0, min_step_quality = 0, ) @test fit_geo_auto_wt.converged @test maximum(abs.(fit_wt.param - [1.0, 2.0])) < 1e-1 @test maximum(abs.(fit_wt.param - fit_geo_wt.param)) < 1e-6 @test maximum(abs.(fit_wt.param - fit_geo_auto_wt.param)) < 1e-6 end
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
3698
using LsqFit, Test, StableRNGs, NLSolversBase @testset "optimization" begin function f_lm(x) [x[1], 2.0 - x[2]] end function g_lm(x) [1.0 0.0; 0.0 -1.0] end initial_x = [100.0, 100.0] R1 = OnceDifferentiable(f_lm, g_lm, zeros(2), zeros(2); inplace = false) results = LsqFit.levenberg_marquardt(R1, initial_x) @assert norm(results.minimizer - [0.0, 2.0]) < 0.01 function rosenbrock_res(r, x) r[1] = 10.0 * (x[2] - x[1]^2) r[2] = 1.0 - x[1] return r end function rosenbrock_jac(j, x) j[1, 1] = -20.0 * x[1] j[1, 2] = 10.0 j[2, 1] = -1.0 j[2, 2] = 0.0 return j end initial_xrb = [-1.2, 1.0] R2 = OnceDifferentiable( rosenbrock_res, rosenbrock_jac, zeros(2), zeros(2); inplace = true, ) results = LsqFit.levenberg_marquardt(R2, initial_xrb) @assert norm(results.minimizer - [1.0, 1.0]) < 0.01 # check estimate is within the bound PR #278 result = LsqFit.levenberg_marquardt( R2, [150.0, 150.0]; lower = [10.0, 10.0], upper = [200.0, 200.0], ) @test LsqFit.minimizer(result)[1] >= 10.0 @test LsqFit.minimizer(result)[2] >= 10.0 let rng = StableRNG(12345) model(x, p) = @. p[1] * exp(-x * p[2]) _nobs = 20 xdata = range(0, stop = 10, length = _nobs) ydata = model(xdata, [1.0 2.0]) + 0.01 * randn(rng, _nobs) f_lsq = p -> model(xdata, p) - ydata g_lsq = p -> NLSolversBase.FiniteDiff.finite_difference_jacobian(f_lsq, p) R3 = OnceDifferentiable(f_lsq, g_lsq, zeros(2), zeros(_nobs); inplace = false) results = LsqFit.levenberg_marquardt(R3, [0.5, 0.5]) @assert norm(results.minimizer - [1.0, 2.0]) < 0.05 end let rng = StableRNG(12345) # TODO: Change to `.-x` when 0.5 support is dropped model(x, p) = @. p[1] * exp(x / p[2]) + p[3] xdata = 1:100 p_generate = [10.0, 10.0, 10.0] ydata = model(xdata, p_generate) + 0.1 * randn(rng, length(xdata)) f_lsq = p -> model(xdata, p) - ydata g_lsq = p -> NLSolversBase.FiniteDiff.finite_difference_jacobian(f_lsq, p) R4 = OnceDifferentiable( f_lsq, g_lsq, similar(p_generate), zeros(length(xdata)); inplace = false, ) # tests for box constraints, PR #196 @test_throws ArgumentError LsqFit.levenberg_marquardt( R4, [15.0, 15.0, 15.0], lower = [5.0, 11.0], ) @test_throws ArgumentError LsqFit.levenberg_marquardt( R4, [5.0, 5.0, 5.0], upper = [15.0, 9.0], ) @test_throws ArgumentError LsqFit.levenberg_marquardt( R4, [15.0, 10.0, 15.0], lower = [5.0, 11.0, 5.0], ) @test_throws ArgumentError LsqFit.levenberg_marquardt( R4, [5.0, 10.0, 5.0], upper = [15.0, 9.0, 15.0], ) lower = [5.0, 11.0, 5.0] results = LsqFit.levenberg_marquardt(R4, [15.0, 15.0, 15.0], lower = lower) results.minimizer @test LsqFit.isconverged(results) @test all(results.minimizer .>= lower) upper = [15.0, 9.0, 15.0] results = LsqFit.levenberg_marquardt(R4, [5.0, 5.0, 5.0], upper = upper) results.minimizer @test LsqFit.isconverged(results) @test all(results.minimizer .<= upper) # tests for PR #267 LsqFit.levenberg_marquardt(R4, [15.0, 15.0, 15.0], show_trace = true) end end
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
code
278
# # Correctness Tests # using LsqFit, Test, LinearAlgebra using NLSolversBase my_tests = ["curve_fit.jl", "levenberg_marquardt.jl", "curve_fit_inplace.jl", "geodesic.jl"] println("Running tests:") for my_test in my_tests println(" * $(my_test)") include(my_test) end
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
docs
11131
LsqFit.jl =========== The LsqFit package is a small library that provides basic least-squares fitting in pure Julia under an MIT license. The basic functionality was originally in [Optim.jl](https://github.com/JuliaNLSolvers/Optim.jl), before being separated into this library. At this time, `LsqFit` only utilizes the Levenberg-Marquardt algorithm for non-linear fitting. [![CI](https://github.com/JuliaNLSolvers/LsqFit.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/JuliaNLSolvers/LsqFit.jl/actions/workflows/ci.yml) [![latest](https://img.shields.io/badge/docs-latest-blue.svg)](https://julianlsolvers.github.io/LsqFit.jl/latest/) Basic Usage ----------- There are top-level methods `curve_fit()` and `margin_error()` that are useful for fitting data to non-linear models. See the following example. Let's first define the model function: ```julia using LsqFit # a two-parameter exponential model # x: array of independent variables # p: array of model parameters # model(x, p) will accept the full data set as the first argument `x`. # This means that we need to write our model function so it applies # the model to the full dataset. We use `@.` to apply the calculations # across all rows. @. model(x, p) = p[1]*exp(-x*p[2]) ``` The function applies the per observation function `p[1]*exp(-x[i]*p[2])` to the full dataset in `x`, with `i` denoting an observation row. We simulate some data and chose our "true" parameters. ```julia # some example data # xdata: independent variables # ydata: dependent variable xdata = range(0, stop=10, length=20) ydata = model(xdata, [1.0 2.0]) + 0.01*randn(length(xdata)) p0 = [0.5, 0.5] ``` Now, we're ready to fit the model. ```julia fit = curve_fit(model, xdata, ydata, p0) # fit is a composite type (LsqFitResult), with some interesting values: # dof(fit): degrees of freedom # coef(fit): best fit parameters # fit.resid: residuals = vector of residuals # fit.jacobian: estimated Jacobian at solution lb = [1.1, -0.5] ub = [1.9, Inf] p0_bounds = [1.2, 1.2] # we have to start inside the bounds # Optional upper and/or lower bounds on the free parameters can be passed as an argument. # Bounded and unbouded variables can be mixed by setting `-Inf` if no lower bounds # is to be enforced for that variable and similarly for `+Inf` fit_bounds = curve_fit(model, xdata, ydata, p0_bounds, lower=lb, upper=ub) # We can estimate errors on the fit parameters, # to get standard error of each parameter: sigma = stderror(fit) # to get margin of error and confidence interval of each parameter at 5% significance level: margin_of_error = margin_error(fit, 0.05) confidence_inter = confint(fit; level=0.95) # The finite difference method is used above to approximate the Jacobian. # Alternatively, a function which calculates it exactly can be supplied instead. function jacobian_model(x,p) J = Array{Float64}(undef, length(x), length(p)) @. J[:,1] = exp(-x*p[2]) #dmodel/dp[1] @. @views J[:,2] = -x*p[1]*J[:,1] #dmodel/dp[2], thanks to @views we don't allocate memory for the J[:,1] slice J end fit = curve_fit(model, jacobian_model, xdata, ydata, p0) ``` Multivariate regression ----------------------- There's nothing inherently different if there are more than one variable entering the problem. We just need to specify the columns appropriately in our model specification. ```julia using LsqFit x = collect(range(0, stop=200, length=201)) y = collect(range(0, stop=200, length=201)) xy = hcat(x, y) function twoD_Gaussian(xy, p) amplitude, xo, yo, sigma_x, sigma_y, theta, offset = p a = (cos(theta)^2)/(2*sigma_x^2) + (sin(theta)^2)/(2*sigma_y^2) b = -(sin(2*theta))/(4*sigma_x^2) + (sin(2*theta))/(4*sigma_y^2) c = (sin(theta)^2)/(2*sigma_x^2) + (cos(theta)^2)/(2*sigma_y^2) # creating linear meshgrid from xy x = xy[:, 1] y = xy[:, 2] g = offset .+ amplitude .* exp.( - (a.*((x .- xo).^2) + 2 .* b .* (x .- xo) .* (y .- yo) + c * ((y .- yo).^2))) return g[:] end p0 = Float64.([3, 100, 100, 20, 40, 0, 10]) data = twoD_Gaussian(xy, p0) # Noisy data data_noisy = data + 0.2 * randn(size(data)) fit = LsqFit.curve_fit(twoD_Gaussian, xy, data_noisy, p0) ``` Evaluating the Jacobian and using automatic differentiation ------------------------- The default is to calculate the Jacobian using a central finite differences scheme if no Jacobian function is provided. The default is to use central differences because it can be more accurate than forward finite differences, but at the expense of computational cost. It is possible to switch to forward finite differences, like MINPACK uses for example, by specifying ```julia fit = curve_fit(model, xdata, ydata, p0; autodiff=:finiteforward) ``` It is also possible to use forward mode automatic differentiation as implemented in ForwardDiff.jl by using the `autodiff=:forwarddiff` keyword. ```julia fit = curve_fit(model, xdata, ydata, p0; autodiff=:forwarddiff) ``` Here, you have to be careful not to manually restrict any types in your code to, say, `Float64`, because ForwardDiff.jl works by passing a special number type through your functions, to auto*magically* calculate the value and gradient with one evaluation. In-place model and Jacobian ------------------------- It is possible to either use an in-place model, or an in-place model *and* an in-place Jacobian. It might be pertinent to use this feature when `curve_fit` is slow, or consumes a lot of memory. ```julia model_inplace(F, x, p) = (@. F = p[1] * exp(-x * p[2])) function jacobian_inplace(J::Array{Float64,2},x,p) @. J[:,1] = exp(-x*p[2]) @. @views J[:,2] = -x*p[1]*J[:,1] end fit = curve_fit(model_inplace, jacobian_inplace, xdata, ydata, p0; inplace = true) ``` Geodesic acceleration --------------------- This package implements optional geodesic acceleration, as outlined by [this paper](https://arxiv.org/pdf/1010.1449.pdf). To enable it, one needs to specify the function computing the *[directional second derivative](https://math.stackexchange.com/questions/2342410/why-is-mathbfdt-h-mathbfd-the-second-directional-derivative)* of the function that is fitted, as the `avv!` parameter. It is also preferable to set `lambda` and `min_step_quality`to `0`: ```julia curve_fit(model, xdata, ydata, p0; avv! = Avv!,lambda=0, min_step_quality = 0) ``` `Avv!` must have the following form: * `p` is the array of parameters * `v`is the direction in which the direction is taken * `dir_deriv` is the output vector (the function is necessarily in-place) ```julia function Avv!(dir_deriv,p,v) v1 = v[1] v2 = v[2] for i=1:length(xdata) #compute all the elements of the Hessian matrix h11 = 0 h12 = (-xdata[i] * exp(-xdata[i] * p[2])) #h21 = h12 h22 = (xdata[i]^2 * p[1] * exp(-xdata[i] * p[2])) # manually compute v'Hv. This whole process might seem cumbersome, but # allocating temporary matrices quickly becomes REALLY expensive and might even # render the use of geodesic acceleration terribly inefficient dir_deriv[i] = h11*v1^2 + 2*h12*v1*v2 + h22*v2^2 end end ``` Typically, if the model to fit outputs `[y_1(x),y_2(x),...,y_m(x)]`, and that the input data is `xdata` then `Avv!`should output an array of size `m`, where each element is `v'*H_i(xdata,p)*v`, where `H_i`is the Hessian matrix of the output `y_i`with respect to the parameter vector `p`. Depending on the size of the dataset, the complexity of the model and the desired tolerance in the fit result, it may be worthwhile to use automatic differentiation (e.g. via `Zygote.jl` or `ForwardDiff.jl`) to determine the directional derivative. Although this is potentially less efficient than calculating the directional derivative manually, this additional information will generally lead to more accurate results. An example of such an implementation is given by: ```julia using LinearAlgebra, Zygote function Avv!(dir_deriv,p,v) for i=1:length(xdata) dir_deriv[i] = transpose(v) * Zygote.hessian(z->model(xdata[i],z),p) * v end end ``` Existing Functionality ---------------------- `fit = curve_fit(model, [jacobian], x, y, [w,] p0; kwargs...)`: * `model`: function that takes two arguments (x, params) * `jacobian`: (optional) function that returns the Jacobian matrix of `model` * `x`: the independent variable * `y`: the dependent variable that constrains `model` * `w`: (optional) weight applied to the residual; can be a vector (of `length(x)` size or empty) or matrix (inverse covariance matrix) * `p0`: initial guess of the model parameters * `kwargs`: tuning parameters for fitting, passed to `levenberg_marquardt`, such as `maxIter`, `show_trace` or `lower` and `upper` bounds * `fit`: composite type of results (`LsqFitResult`) This performs a fit using a non-linear iteration to minimize the (weighted) residual between the model and the dependent variable data (`y`). The weight (`w`) can be neglected (as per the example) to perform an unweighted fit. An unweighted fit is the numerical equivalent of `w=1` for each point (although unweighted error estimates are handled differently from weighted error estimates even when the weights are uniform). ---- `sigma = stderror(fit; atol, rtol)`: * `fit`: result of curve_fit (a `LsqFitResult` type) * `atol`: absolute tolerance for negativity check * `rtol`: relative tolerance for negativity check This returns the error or uncertainty of each parameter fit to the model and already scaled by the associated degrees of freedom. Please note, this is a LOCAL quantity calculated from the Jacobian of the model evaluated at the best fit point and NOT the result of a parameter exploration. If no weights are provided for the fits, the variance is estimated from the mean squared error of the fits. If weights are provided, the weights are assumed to be the inverse of the variances or of the covariance matrix, and errors are estimated based on these and the Jacobian, assuming a linearization of the model around the minimum squared error point. `margin_of_error = margin_error(fit, alpha=0.05; atol, rtol)`: * `fit`: result of curve_fit (a `LsqFitResult` type) * `alpha`: significance level * `atol`: absolute tolerance for negativity check * `rtol`: relative tolerance for negativity check This returns the product of standard error and critical value of each parameter at `alpha` significance level. `confidence_interval = confint(fit; level=0.05, atol, rtol)`: * `fit`: result of curve_fit (a `LsqFitResult` type) * `level`: confidence level * `atol`: absolute tolerance for negativity check * `rtol`: relative tolerance for negativity check This returns confidence interval of each parameter at `level` significance level. ---- `covar = vcov(fit)`: * `fit`: result of curve_fit (a `LsqFitResult` type) * `covar`: parameter covariance matrix calculated from the Jacobian of the model at the fit point, using the weights (if specified) as the inverse covariance of observations This returns the parameter covariance matrix evaluated at the best fit point.
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
docs
302
# TODO for Optim.jl * more tests for curve_fit() * more documentation # Things to consider * tweak a lighterweight package that does not have Distribution dependency? * simple linear fitting? * use DualNumbers for finite difference (like in Optim.jl)? * add algorithms besides Levenberg-Marquardt?
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
docs
107
# API ```@autodocs Modules = [LsqFit] Private = false Pages = ["curve_fit.jl"] Order = [:function] ```
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
docs
1893
# Getting Started First, import the package. ```julia julia> using LsqFit ``` Define a two-parameter exponential decay model, where ``t`` is a one-element independent variable, ``p_1`` and ``p_2`` are parameters. The model function is: ```math m(t, \boldsymbol{p}) = p_1 \exp(-p_2 t) ``` ```julia julia> # t: array of independent variable julia> # p: array of model parameters julia> model(t, p) = p[1] * exp.(-p[2] * t) ``` For illustration purpose, we generate some fake data. ```julia julia> # tdata: data of independent variable julia> # ydata: data of dependent variable julia> tdata = range(0, stop=10, length=20) julia> ydata = model(tdata, [1.0 2.0]) + 0.01*randn(length(tdata)) ``` Before fitting the data, we also need a initial value of parameters for `curve_fit()`. ```julia julia> p0 = [0.5, 0.5] ``` Run `curve_fit()` to fit the data and get the estimated parameters. ```julia julia> fit = curve_fit(model, tdata, ydata, p0) julia> param = fit.param 2-element Array{Float64,1}: 1.01105 2.0735 ``` `LsqFit.jl` also provides functions to examinep0 = [0.5, 0.5] the goodness of fit. `vcov(fit)` computes the estimated covariance matrix. ```Julia julia> cov = vcov(fit) 2×2 Array{Float64,2}: 0.000116545 0.000174633 0.000174633 0.00258261 ``` `stderror(fit)` returns the standard error of each parameter. ```Julia julia> se = stderror(fit) 2-element Array{Float64,1}: 0.0107956 0.0508193 ``` To get the confidence interval at 10% significance level, run `confint(fit; level=0.9)`, which essentially computes `the estimate parameter value` ± (`standard error` * `critical value from t-distribution`). ```Julia julia> confidence_interval = confint(fit; level=0.9) 2-element Array{Tuple{Float64,Float64},1}: (0.992333, 1.02977) (1.98537, 2.16162) ``` For more details of `LsqFit.jl`, check [Tutorial](./tutorial.md) and [API References](./api.md) section.
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
docs
1358
# LsqFit.jl Basic least-squares fitting in pure Julia under an MIT license. The basic functionality was originaly in [Optim.jl](https://github.com/JuliaNLSolvers/Optim.jl), before being separated into this library. At this time, `LsqFit` only utilizes the Levenberg-Marquardt algorithm for non-linear fitting. `LsqFit.jl` is part of the [JuliaNLSolvers](https://github.com/JuliaNLSolvers) family. |Source|Package Evaluator|Build Status| |:----:|:---------------:|:----------:| | [![Source](https://img.shields.io/badge/GitHub-source-green.svg)](https://github.com/JuliaNLSolvers/Optim.jl) |[![LsqFit](http://pkg.julialang.org/badges/LsqFit_0.4.svg)](http://pkg.julialang.org/?pkg=LsqFit&ver=0.4) [![LsqFit](http://pkg.julialang.org/badges/LsqFit_0.5.svg)](http://pkg.julialang.org/?pkg=LsqFit&ver=0.5) [![LsqFit](http://pkg.julialang.org/badges/LsqFit_0.6.svg)](http://pkg.julialang.org/?pkg=LsqFit&ver=0.6) [![LsqFit](http://pkg.julialang.org/badges/LsqFit_0.7.svg)](http://pkg.julialang.org/?pkg=LsqFit&ver=0.7)|[![Build Status](https://travis-ci.org/JuliaNLSolvers/LsqFit.jl.svg)](https://travis-ci.org/JuliaNLSolvers/LsqFit.jl)| ## Install To install the package, run ```julia Pkg.add("LsqFit") ``` If you want the latest features, also run ```julia Pkg.checkout("LsqFit") ``` To use the package in your code ```julia julia> using LsqFit ```
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MIT" ]
0.15.0
40acc20cfb253cf061c1a2a2ea28de85235eeee1
docs
16132
# Tutorial ## Introduction to Nonlinear Regression Assume that, for the $i$th observation, the relationship between independent variable $\mathbf{x_i}=\begin{bmatrix} x_{1i},\, x_{2i},\, \ldots\, x_{pi}\ \end{bmatrix}'$ and dependent variable $Y_i$ follows: ```math Y_i = m(\mathbf{x_i}, \boldsymbol{\gamma}) + \epsilon_i ``` where $m$ is a non-linear model function depends on the independent variable $\mathbf{x_i}$ and the parameter vector $\boldsymbol{\gamma}$. In order to find the parameter $\boldsymbol{\gamma}$ that "best" fit our data, we choose the parameter ${\boldsymbol{\gamma}}$ which minimizes the sum of squared residuals from our data, i.e. solves the problem: ```math \underset{\boldsymbol{\gamma}}{\mathrm{min}} \quad s(\boldsymbol{\gamma})= \sum_{i=1}^{n} [m(\mathbf{x_i}, \boldsymbol{\gamma}) - y_i]^2 ``` Given that the function $m$ is non-linear, there's no analytical solution for the best $\boldsymbol{\gamma}$. We have to use computational tools, which is `LsqFit.jl` in this tutorial, to find the least squares solution. One example of non-linear model is the exponential model, which takes a one-element predictor variable $t$. The model function is: ```math m(t, \boldsymbol{\gamma}) = \gamma_1 \exp(\gamma_2 t) ``` and the model becomes: ```math Y_i = \gamma_1 \exp(\gamma_2 t_i) + \epsilon_i ``` To fit data using `LsqFit.jl`, pass the defined model function (`m`), data (`tdata` and `ydata`) and the initial parameter value (`p0`) to `curve_fit()`. For now, `LsqFit.jl` only supports the Levenberg Marquardt algorithm. ```julia julia> # t: array of independent variables julia> # p: array of model parameters julia> m(t, p) = p[1] * exp.(p[2] * t) julia> p0 = [0.5, 0.5] julia> fit = curve_fit(m, tdata, ydata, p0) ``` It will return a composite type `LsqFitResult`, with some interesting values: * `dof(fit)`: degrees of freedom * `coef(fit)`: best fit parameters * `fit.resid`: vector of residuals * `fit.jacobian`: estimated Jacobian at the solution ## Jacobian Calculation The Jacobian $J_f(\mathbf{x})$ of a vector function $f(\mathbf{x}): \mathbb{R}_m \to \mathbb{R}_n$ is defined as the matrix with elements: ```math [J_f(\mathbf{x})]_{ij} = \frac{\partial f_i(\mathbf{x})}{\partial x_j} ``` The matrix is therefore: ```math J_f(\mathbf{x}) = \begin{bmatrix} \frac{\partial f_1}{\partial x_1}&\frac{\partial f_1}{\partial x_2}&\dots&\frac{\partial f_1}{\partial x_m}\\ \frac{\partial f_2}{\partial x_1}&\frac{\partial f_2}{\partial x_2}&\dots&\frac{\partial f_2}{\partial x_m}\\ \vdots&\vdots&\ddots&\vdots\\ \frac{\partial f_n}{\partial x_1}&\frac{\partial f_n}{\partial x_2}&\dots&\frac{\partial f_n}{\partial x_m}\\ \end{bmatrix} ``` The Jacobian of the exponential model function with respect to $\boldsymbol{\gamma}$ is: ```math J_m(t, \boldsymbol{\gamma}) = \begin{bmatrix} \frac{\partial m}{\partial \gamma_1} & \frac{\partial m}{\partial \gamma_2} \\ \end{bmatrix} = \begin{bmatrix} \exp(\gamma_2 t) & t \gamma_1 \exp(\gamma_2 t) \\ \end{bmatrix} ``` By default, the finite differences is used (see [NLSolversBase.jl](https://github.com/JuliaNLSolvers/NLSolversBase.jl) for more information), is used to approximate the Jacobian for the data fitting algorithm and covariance computation. Alternatively, a function which calculates the Jacobian can be supplied to `curve_fit()` for faster and/or more accurate results. ```Julia function j_m(t,p) J = Array{Float64}(length(t),length(p)) J[:,1] = exp.(p[2] .* t) #df/dp[1] J[:,2] = t .* p[1] .* J[:,1] #df/dp[2] J end fit = curve_fit(m, j_m, tdata, ydata, p0) ``` ## Linear Approximation The non-linear function $m$ can be approximated as a linear function by Talor expansion: ```math m(\mathbf{x_i}, \boldsymbol{\gamma}+\boldsymbol{h}) \approx m(\mathbf{x_i}, \boldsymbol{\gamma}) + \nabla m(\mathbf{x_i}, \boldsymbol{\gamma})'\boldsymbol{h} ``` where $\boldsymbol{\gamma}$ is a fixed vector, $\boldsymbol{h}$ is a very small-valued vector and $\nabla m(\mathbf{x_i}, \boldsymbol{\gamma})$ is the gradient at $\mathbf{x_i}$. Consider the residual vector functon $r({\boldsymbol{\gamma}})=\begin{bmatrix} r_1({\boldsymbol{\gamma}}) \\ r_2({\boldsymbol{\gamma}}) \\ \vdots\\ r_n({\boldsymbol{\gamma}}) \end{bmatrix}$ with entries: ```math r_i({\boldsymbol{\gamma}}) = m(\mathbf{x_i}, {\boldsymbol{\gamma}}) - Y_i ``` Each entry's linear approximation can hence be written as: ```math \begin{align} r_i({\boldsymbol{\gamma}}+\boldsymbol{h}) &= m(\mathbf{x_i}, \boldsymbol{\gamma}+\boldsymbol{h}) - Y_i\\ &\approx m(\mathbf{x_i}, \boldsymbol{\gamma}) + \nabla m(\mathbf{x_i}, \boldsymbol{\gamma})'h - Y_i\\ &= r_i({\boldsymbol{\gamma}}) + \nabla m(\mathbf{x_i}, \boldsymbol{\gamma})'h \end{align} ``` Since the $i$th row of $J(\boldsymbol{\gamma})$ equals the transpose of the gradient of $m(\mathbf{x_i}, \boldsymbol{\gamma})$, the vector function $r({\boldsymbol{\gamma}}+\boldsymbol{h})$ can be approximated as: ```math r({\boldsymbol{\gamma}}+\boldsymbol{h}) \approx r({\boldsymbol{\gamma}}) + J(\boldsymbol{\gamma})h ``` which is a linear function on $\boldsymbol{h}$ since ${\boldsymbol{\gamma}}$ is a fixed vector. ## Goodness of Fit The linear approximation of the non-linear least squares problem leads to the approximation of the covariance matrix of each parameter, from which we can perform regression analysis. Consider a least squares solution $\boldsymbol{\gamma}^*$, which is a local minimizer of the non-linear problem: ```math \boldsymbol{\gamma}^* = \underset{\boldsymbol{\gamma}}{\mathrm{arg\,min}} \ \sum_{i=1}^{n} [m(\mathbf{x_i}, \boldsymbol{\gamma}) - y_i]^2 ``` Set $\boldsymbol{\gamma}^*$ as the fixed point in linear approximation, $r({\boldsymbol{\gamma^*}}) = r$ and $J(\boldsymbol{\gamma^*}) = J$. A parameter vector near $\boldsymbol{\gamma}^*$ can be expressed as $\boldsymbol{\gamma}=\boldsymbol{\gamma^*} + h$. The local approximation for the least squares problem is: ```math \underset{\boldsymbol{\gamma}}{\mathrm{min}} \quad s(\boldsymbol{\gamma})=s(\boldsymbol{\gamma}^*+\boldsymbol{h}) \approx [Jh + r]'[Jh + r] ``` which is essentially the linear least squares problem: ```math \underset{\boldsymbol{\beta}}{\mathrm{min}} \quad [X\beta-Y]'[X\beta-Y] ``` where $X=J$, $\beta=\boldsymbol{h}$ and $Y=-r({\boldsymbol{\gamma}})$. Solve the equation where the partial derivatives equal to $0$, the analytical solution is: ```math \hat{\boldsymbol{h}}=\hat{\boldsymbol{\gamma}}-\boldsymbol{\gamma}^*\approx-[J'J]^{-1}J'r ``` The covariance matrix for the analytical solution is: ```math \mathbf{Cov}(\hat{\boldsymbol{\gamma}}) = \mathbf{Cov}(\boldsymbol{h}) = [J'J]^{-1}J'\mathbf{E}(rr')J[J'J]^{-1} ``` Note that $r$ is the residual vector at the best fit point $\boldsymbol{\gamma^*}$, with entries $r_i = Y_i - m(\mathbf{x_i}, \boldsymbol{\gamma^*})=\epsilon_i$. $\hat{\boldsymbol{\gamma}}$ is very close to $\boldsymbol{\gamma^*}$ and therefore can be replaced by $\boldsymbol{\gamma^*}$. ```math \mathbf{Cov}(\boldsymbol{\gamma}^*) \approx \mathbf{Cov}(\hat{\boldsymbol{\gamma}}) ``` Assume the errors in each sample are independent, normal distributed with zero mean and same variance, i.e. $\epsilon \sim N(0, \sigma^2I)$, the covariance matrix from the linear approximation is therefore: ```math \mathbf{Cov}(\boldsymbol{\gamma}^*) = [J'J]^{-1}J'\mathbf{Cov}(\epsilon)J[J'J]^{-1} = \sigma^2[J'J]^{-1} ``` where $\sigma^2$ could be estimated as residual sum of squares devided by degrees of freedom: ```math \hat{\sigma}^2=\frac{s(\boldsymbol{\gamma}^*)}{n-p} ``` In `LsqFit.jl`, the covariance matrix calculation uses QR decomposition to [be more computationally stable](http://www.seas.ucla.edu/~vandenbe/133A/lectures/ls.pdf), which has the form: ```math \mathbf{Cov}(\boldsymbol{\gamma}^*) = \hat{\sigma}^2 \mathrm{R}^{-1}(\mathrm{R}^{-1})' ``` `vcov()` computes the covariance matrix of fit: ```Julia julia> cov = vcov(fit) 2×2 Array{Float64,2}: 0.000116545 0.000174633 0.000174633 0.00258261 ``` The standard error is then the square root of each diagonal elements of the covariance matrix. `stderror()` returns the standard error of each parameter: ```Julia julia> se = stderror(fit) 2-element Array{Float64,1}: 0.0114802 0.0520416 ``` `margin_error()` computes the product of standard error and the critical value of each parameter at a certain significance level (default is 5%) from t-distribution. The margin of error at 10% significance level can be computed by: ```Julia julia> margin_of_error = margin_error(fit, 0.1) 2-element Array{Float64,1}: 0.0199073 0.0902435 ``` `confint()` returns the confidence interval of each parameter at certain significance level, which is essentially the estimate value ± margin of error. To get the confidence interval at 10% significance level, run: ```Julia julia> confidence_intervals = confint(fit; level=0.9) 2-element Array{Tuple{Float64,Float64},1}: (0.976316, 1.01613) (1.91047, 2.09096) ``` ## Weighted Least Squares `curve_fit()` also accepts weight parameter (`wt`) to perform Weighted Least Squares and General Least Squares, where the parameter $\boldsymbol{\gamma}^*$ minimizes the weighted residual sum of squares. Weight parameter (`wt`) is an array or a matrix of weights for each sample. To perform Weighted Least Squares, pass the weight array `[w_1, w_2, ..., w_n]` or the weight matrix `W`: ```math \mathbf{W} = \begin{bmatrix} w_1 & 0 & \cdots & 0\\ 0 & w_2 & \cdots & 0\\ \vdots & \vdots & \ddots & \vdots\\ 0 & 0 & \cdots & w_n\\ \end{bmatrix} ``` The weighted least squares problem becomes: ```math \underset{\boldsymbol{\gamma}}{\mathrm{min}} \quad s(\boldsymbol{\gamma})= \sum_{i=1}^{n} w_i[m(\mathbf{x_i}, \boldsymbol{\gamma}) - Y_i]^2 ``` in matrix form: ```math \underset{\boldsymbol{\gamma}}{\mathrm{min}} \quad s(\boldsymbol{\gamma})= r(\boldsymbol{\gamma})'Wr(\boldsymbol{\gamma}) ``` where $r({\boldsymbol{\gamma}})=\begin{bmatrix} r_1({\boldsymbol{\gamma}}) \\ r_2({\boldsymbol{\gamma}}) \\ \vdots\\ r_n({\boldsymbol{\gamma}}) \end{bmatrix}$ is a residual vector function with entries: ```math r_i({\boldsymbol{\gamma}}) = m(\mathbf{x_i}, {\boldsymbol{\gamma}}) - Y_i ``` The algorithm in `LsqFit.jl` will then provide a least squares solution $\boldsymbol{\gamma}^*$. !!! note In `LsqFit.jl`, the residual function passed to `levenberg_marquardt()` is in different format, if the weight is a vector: ```julia r(p) = sqrt.(wt) .* ( model(xpts, p) - ydata ) lmfit(r, g, p0, wt; kwargs...) ``` ```math r_i({\boldsymbol{\gamma}}) = \sqrt{w_i} \cdot [m(\mathbf{x_i}, {\boldsymbol{\gamma}}) - Y_i] ``` Cholesky decomposition, which is effectively a sqrt of a matrix, will be performed if the weight is a matrix: ```julia u = chol(wt) r(p) = u * ( model(xpts, p) - ydata ) lmfit(r, p0, wt; kwargs...) ``` ```math r_i({\boldsymbol{\gamma}}) = \sqrt{w_i} \cdot [m(\mathbf{x_i}, {\boldsymbol{\gamma}}) - Y_i] ``` The solution will be the same as the least squares problem mentioned in the tutorial. Set $r({\boldsymbol{\gamma^*}}) = r$ and $J(\boldsymbol{\gamma^*}) = J$, the linear approximation of the weighted least squares problem is then: ```math \underset{\boldsymbol{\gamma}}{\mathrm{min}} \quad s(\boldsymbol{\gamma}) = s(\boldsymbol{\gamma}^* + \boldsymbol{h}) \approx [J\boldsymbol{h}+r]'W[J\boldsymbol{h}+r] ``` The analytical solution to the linear approximation is: ```math \hat{\boldsymbol{h}}=\hat{\boldsymbol{\gamma}}-\boldsymbol{\gamma}^*\approx-[J'WJ]^{-1}J'Wr ``` Assume the errors in each sample are independent, normal distributed with zero mean and **different** variances (heteroskedastic error), i.e. $\epsilon \sim N(0, \Sigma)$, where: ```math \Sigma = \begin{bmatrix} \sigma_1^2 & 0 & \cdots & 0\\ 0 & \sigma_2^2 & \cdots & 0\\ \vdots & \vdots & \ddots & \vdots\\ 0 & 0 & \cdots & \sigma_n^2\\ \end{bmatrix} ``` We know the error variance and we set the weight as the inverse of the variance (the optimal weight), i.e. $W = \Sigma^{-1}$: ```math \mathbf{W} = \begin{bmatrix} w_1 & 0 & \cdots & 0\\ 0 & w_2 & \cdots & 0\\ \vdots & \vdots & \ddots & \vdots\\ 0 & 0 & \cdots & w_n\\ \end{bmatrix} = \begin{bmatrix} \frac{1}{\sigma_1^2} & 0 & \cdots & 0\\ 0 & \frac{1}{\sigma_2^2} & \cdots & 0\\ \vdots & \vdots & \ddots & \vdots\\ 0 & 0 & \cdots & \frac{1}{\sigma_n^2}\\ \end{bmatrix} ``` The covariance matrix is now: ```math {Cov}(\boldsymbol{\gamma}^*) \approx [J'WJ]^{-1}J'W \Sigma W'J[J'W'J]^{-1} = [J'WJ]^{-1} ``` If we only know **the relative ratio of different variances**, i.e. $\epsilon \sim N(0, \sigma^2W^{-1})$, the covariance matrix will be: ```math \mathbf{Cov}(\boldsymbol{\gamma}^*) = \sigma^2[J'WJ]^{-1} ``` where $\sigma^2$ is estimated. In this case, if we set $W = I$, the result will be the same as the unweighted version. However, `curve_fit()` currently **does not support** this implementation. `curve_fit()` assumes the weight as the inverse of **the error covariance matrix** rather than **the ratio of error covariance matrix**, i.e. the covariance of the estimated parameter is calculated as `covar = inv(J'*fit.wt*J)`. !!! note Passing vector of ones as the weight vector will cause mistakes in covariance estimation. Pass the vector of `1 ./ var(ε)` or the matrix `inv(covar(ε))` as the weight parameter (`wt`) to the function `curve_fit()`: ```Julia julia> wt = inv(cov_ε) julia> fit = curve_fit(m, tdata, ydata, wt, p0) julia> cov = vcov(fit) ``` !!! note If the weight matrix is not a diagonal matrix, General Least Squares will be performed. ## General Least Squares Assume the errors in each sample are **correlated**, normal distributed with zero mean and **different** variances (heteroskedastic and autocorrelated error), i.e. $\epsilon \sim N(0, \Sigma)$. Set the weight matrix as the inverse of the error covariance matrix (the optimal weight), i.e. $W = \Sigma^{-1}$, we will get the parameter covariance matrix: ```math \mathbf{Cov}(\boldsymbol{\gamma}^*) \approx [J'WJ]^{-1}J'W \Sigma W'J[J'W'J]^{-1} = [J'WJ]^{-1} ``` Pass the matrix `inv(covar(ε))` as the weight parameter (`wt`) to the function `curve_fit()`: ```Julia julia> wt = 1 ./ yvar julia> fit = curve_fit(m, tdata, ydata, wt, p0) julia> cov = vcov(fit) ``` ## Estimate the Optimal Weight In most cases, the variances of errors are unknown. To perform Weighted Least Square, we need estimate the variances of errors first, which is the squared residual of $i$th sample: ```math \widehat{\mathbf{Var}(\epsilon_i)} = \widehat{\mathbf{E}(\epsilon_i \epsilon_i)} = r_i(\boldsymbol{\gamma}^*) ``` Unweighted fitting (OLS) will return the residuals we need, since the estimator of OLS is unbiased. Then pass the reciprocal of the residuals as the estimated optimal weight to perform Weighted Least Squares: ```Julia julia> fit_OLS = curve_fit(m, tdata, ydata, p0) julia> wt = 1 ./ fit_OLS.resid julia> fit_WLS = curve_fit(m, tdata, ydata, wt, p0) julia> cov = vcov(fit_WLS) ``` ## References Hansen, P. C., Pereyra, V. and Scherer, G. (2013) Least squares data fitting with applications. Baltimore, Md: Johns Hopkins University Press, p. 147-155. Kutner, M. H. et al. (2005) Applied Linear statistical models. Weisberg, S. (2014) Applied linear regression. Fourth edition. Hoboken, NJ: Wiley (Wiley series in probability and statistics).
LsqFit
https://github.com/JuliaNLSolvers/LsqFit.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
1276
using ElectronGas using Documenter DocMeta.setdocmeta!(ElectronGas, :DocTestSetup, :(using ElectronGas); recursive=true) makedocs(; modules=[ElectronGas], authors="Kun Chen", repo="https://github.com/numericalEFT/ElectronGas.jl/blob/{commit}{path}#{line}", sitename="ElectronGas.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://numericalEFT.github.io/ElectronGas.jl", assets=String[] ), pages=[ "Home" => "index.md", "Manual" => [ "manual/fock.md", "manual/polarization_3D.md", "manual/polarization_2D.md", "manual/ladder_3D.md", "manual/polarization_approx.md", "manual/legendreinteraction.md", "manual/G_plus_Moroni.md", "manual/quasiparticle.md", ], "Reference" => Any[ "lib/convention.md", "lib/parameter.md", "lib/selfenergy.md", "lib/polarization.md", "lib/interaction.md", "lib/legendreinteraction.md", "lib/twopoint.md", "lib/BSeq.md", ] ] ) deploydocs(; repo="github.com/numericalEFT/ElectronGas.jl", devbranch="master" )
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
1587
""" In this demo, we analysis the contribution of the exchange KO interaction to the Landau parameters """ using ElectronGas, Parameters using Lehmann, GreenFunc, CompositeGrids const rs = 5.0 const beta = 1000.0 const mass2 = 1e-8 const dim = 3 θ = 1e-3 param = Parameter.defaultUnit(θ, rs) kF, β = param.kF, param.β Euv, rtol = 1000 * param.EF, 1e-11 # Nk, order = 8, 4 # maxK, minK = 10kF, 1e-7kF # Nk, order = 11, 8 maxK, minK = 20kF, 1e-8kF Nk, order = 16, 12 # maxK, minK = 10kF, 1e-9kF # Euv, rtol = 1000 * param.EF, 1e-11 # maxK, minK = 20param.kF, 1e-9param.kF # Nk, order = 16, 12 # test G0 kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, maxK], [0.0, kF], Nk, minK, order) G0 = SelfEnergy.G0wrapped(Euv, rtol, kgrid, param) kF_label = searchsortedfirst(kgrid.grid, kF) G_tau = GreenFunc.toTau(G0) # println(G_tau.timeGrid.grid) # println(real(G_tau.dynamic[1, 1, :, end]) .* (-1)) G_ins = tau2tau(G_tau.dlrGrid, G_tau.dynamic, [β,], G_tau.timeGrid.grid; axis=4)[1, 1, :, 1] .* (-1) # println(real(G_ins)) integrand = real(G_ins) .* kgrid.grid .* kgrid.grid density0 = CompositeGrids.Interp.integrate1D(integrand, kgrid) / π^2 # println("$density0, $(param.n)") # @test isapprox(param.n, density0, rtol=3e-5) Σ = SelfEnergy.G0W0(param, Euv, rtol, Nk, maxK, minK, order, :ko) Σ = SelfEnergy.GreenFunc.toMatFreq(Σ) Z0 = (SelfEnergy.zfactor(Σ)) #z = zlist[ind] # @test isapprox(Z0, z, rtol=3e-3) mratio = SelfEnergy.massratio(param, Σ) #m = mlist[ind] # @test isapprox(mratio, m, rtol=3e-3) println("θ = $θ, rs= $rs") println("Z-factor = $Z0") println("m*/m = $mratio")
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
3826
""" calculate the Z factor of UEG using MC """ using Printf, LinearAlgebra using CompositeGrids using ElectronGas using Parameters, Random using MCIntegration using Lehmann const steps = 1e7 # include("parameter.jl") dim = 3 beta = 100.0 rs = 5.0 mass2 = 1.e-3 # const para = Parameter.rydbergUnit(1.0 / beta, rs, dim, Λs = mass2) const para = Parameter.defaultUnit(1.0 / beta, rs, dim, Λs=mass2) const kF = para.kF const EF = para.EF const β = para.β # qgrid = CompositeGrid.LogDensedGrid(:uniform, [0.0, 6 * kF], [0.0, 2kF], 16, 0.01 *kF , 8) qgrid = CompositeGrid.LogDensedGrid(:uniform, [0.0, 6 * kF], [0.0, 2kF], 16, 1e-6 * kF, 8) τgrid = CompositeGrid.LogDensedGrid(:uniform, [0.0, β], [0.0, β], 16, β * 1e-4, 8) # dlr = DLRGrid(Euv = 10EF, β = β, rtol = 1e-10, isFermi = false, symmetry = :ph) # W = zeros(length(qgrid), dlr.size) # for (qi, q) in enumerate(qgrid.grid) # for (ni, n) in enumerate(dlr.n) # # W[qi, ni] = Interaction.RPA(q, n, para, regular = true, pifunc = Polarization.Polarization0_FiniteTemp)[1] # W[qi, ni] = Interaction.RPA(q, n, para, regular = true, pifunc = Polarization.Polarization0_ZeroTemp)[1] # end # end # const dW0 = matfreq2tau(dlr, W, τgrid.grid, axis = 2) Ws, Wa = Interaction.RPAwrapped(10EF, 1e-10, qgrid.grid, para) const dW0 = real.(matfreq2tau(Ws.dlrGrid, Ws.dynamic, τgrid.grid, axis=4))[1, 1, :, :] function integrand(config) if config.curr == 1 return eval2(config) else error("impossible!") end end function interactionDynamic(qd, τIn, τOut) dτ = abs(τOut - τIn) kDiQ = sqrt(dot(qd, qd)) # vd = 4π * para.e0^2 / (kDiQ^2 + para.Λs) vs, va = Interaction.coulomb_2d(kDiQ, para) # vs, va = Interaction.coulomb(kDiQ, para) if kDiQ <= qgrid.grid[1] q = qgrid.grid[1] + 1.0e-6 wd = vs * Interp.linear2D(dW0, qgrid, τgrid, q, dτ) # the current interpolation vanishes at q=0, which needs to be corrected! else wd = vs * Interp.linear2D(dW0, qgrid, τgrid, kDiQ, dτ) # dynamic interaction, don't forget the singular factor vq end return wd end function eval2(config) K, T = config.var[1], config.var[2] k, τ = K[1], T[1] k0 = zeros(para.dim) k0[end] = kF # external momentum kq = k + k0 ω = (dot(kq, kq) - kF^2) / (2 * para.me) g = Spectral.kernelFermiT(τ, ω, β) dW = interactionDynamic(k, 0.0, τ) phase = 1.0 / (2π)^para.dim return g * dW * phase end function measure(config) factor = 1.0 / config.reweight[config.curr] τ = config.var[2][1] # println(config.observable[1][1]) if config.curr == 1 weight = integrand(config) config.observable[1] += weight * sin(π / β * τ) / abs(weight) * factor config.observable[2] += weight * sin(3π / β * τ) / abs(weight) * factor else return end end function fock(extn) K = MCIntegration.FermiK(para.dim, kF, 0.2 * kF, 10.0 * kF) T = MCIntegration.Tau(β, β / 2.0) dof = [[1, 1],] # degrees of freedom of the Fock diagram obs = zeros(2) # observable for the Fock diagram config = MCIntegration.Configuration(steps, (K, T), dof, obs; para=para) avg, std = MCIntegration.sample(config, integrand, measure; print=0, Nblock=16) if isnothing(avg) == false @printf("%10.6f %10.6f ± %10.6f\n", -1.0, avg[1], std[1]) @printf("%10.6f %10.6f ± %10.6f\n", 0.0, avg[2], std[2]) dS_dw = (avg[1] - avg[2]) / (2π / β) error = (std[1] + std[2]) / (2π / β) println("dΣ/diω= $dS_dw ± $error") Z = (1 / (1 + dS_dw)) Zerror = error / Z^2 println("Z= $Z ± $Zerror") # TODO: add errorbar estimation # println end end if abspath(PROGRAM_FILE) == @__FILE__ # using Gaston ngrid = [-1, 0, 1] @time fock(ngrid) end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
3486
""" calculate the Z factor of UEG using MC """ using Printf, LinearAlgebra using CompositeGrids using ElectronGas using Parameters, Random using MCIntegration using Lehmann const steps = 1e6 include("parameter.jl") include("interaction.jl") kgrid = CompositeGrid.LogDensedGrid(:uniform, [0.0, 3kF], [0.0, kF], 8, 0.01 * kF, 8) # external K grid for sigma dlr = DLRGrid(Euv = 10EF, β = β, isFermi = true, rtol = 1e-10) # const basic = Parameter.rydbergUnit(1 / beta, rs, dim, Λs = mass2) struct Para{Q,T} dW0::Matrix{Float64} qgrid::Q τgrid::T # dedicated τgrid for dynamic interaction function Para() qgrid = CompositeGrid.LogDensedGrid(:uniform, [0.0, 6 * kF], [0.0, 2kF], 16, 0.01 * kF, 8) τgrid = CompositeGrid.LogDensedGrid(:uniform, [0.0, β], [0.0, β], 16, β * 1e-4, 8) vqinv = [(q^2 + mass2) / (4π * e0^2) for q in qgrid.grid] # 3D Yukawa # vqinv = [√(q^2 + mass2) / (2π * e0^2) for q in qgrid.grid] # 2D Yukawa dW0 = TwoPoint.dWRPA(vqinv, qgrid.grid, τgrid.grid, dim, EF, kF, β, spin, me) # dynamic part of the effective interaction # dW0 = TwoPoint.dWKO(vqinv, qgrid.grid, τgrid.grid, dim, EF, kF, β, spin, me, fp, fm) # dynamic part of the effective interaction return new{typeof(qgrid),typeof(τgrid)}(dW0, qgrid, τgrid) # Ws, Wa = Interaction.RPAwrapped(10EF, 1e-10, qgrid.grid, basic) # dW0 = real.(matfreq2tau(Ws.dlrGrid, Ws.dynamic, τgrid.grid, axis = 4)) # return new{typeof(qgrid),typeof(τgrid)}(dW0[1, 1, :, :], qgrid, τgrid) end end function integrand(config) if config.curr == 1 return eval2(config) else error("impossible!") end end function eval2(config) para = config.para K, T = config.var[1], config.var[2] k, τ = K[1], T[1] k0 = zeros(dim) k0[end] = kF # external momentum kq = k + k0 ω = (dot(kq, kq) - kF^2) / (2 * me) g = Spectral.kernelFermiT(τ, ω, β) v, dW = interactionDynamic(para, k, 0.0, τ, dim) phase = 1.0 / (2π)^dim return g * dW * phase end function measure(config) factor = 1.0 / config.reweight[config.curr] τ = config.var[2][1] # println(config.observable[1][1]) if config.curr == 1 weight = integrand(config) config.observable[1] += weight * sin(π / β * τ) / abs(weight) * factor config.observable[2] += weight * sin(3π / β * τ) / abs(weight) * factor else return end end function fock(extn) para = Para() Ksize = length(kgrid.grid) K = MCIntegration.FermiK(dim, kF, 0.2 * kF, 10.0 * kF) T = MCIntegration.Tau(β, β / 2.0) # Ext = dof = [[1, 1],] # degrees of freedom of the Fock diagram obs = zeros(2) # observable for the Fock diagram config = MCIntegration.Configuration(steps, (K, T), dof, obs; para = para) avg, std = MCIntegration.sample(config, integrand, measure; print = 0, Nblock = 16) if isnothing(avg) == false @printf("%10.6f %10.6f ± %10.6f\n", -1.0, avg[1], std[1]) @printf("%10.6f %10.6f ± %10.6f\n", 0.0, avg[2], std[2]) dS_dw = (avg[1] - avg[2]) / (2π / β) error = (std[1] + std[2]) / (2π / β) println("dΣ/diω= $dS_dw ± $error") Z = (1 / (1 + dS_dw)) Zerror = error / Z^2 println("Z= $Z ± $Zerror") # TODO: add errorbar estimation # println end end if abspath(PROGRAM_FILE) == @__FILE__ # using Gaston ngrid = [-1, 0, 1] @time fock(ngrid) end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
2539
# This example demonstrated how to calculate the bubble diagram of free electrons using the Monte Carlo module using LinearAlgebra, Random, Printf, BenchmarkTools, InteractiveUtils, Parameters using ElectronGas using StaticArrays using Lehmann using MCIntegration # using ProfileView const Steps = 1e7 # include("parameter.jl") beta = 1000.0 rs = 2.0 const basic = Parameter.rydbergUnit(1 / beta, rs, 2) const β = basic.β const kF = basic.kF const me = basic.me const spin = basic.spin @with_kw struct Para dim::Int = 2 n::Int = 10 # external Matsubara frequency Qsize::Int = 16 extQ::Vector{SVector{2,Float64}} = [@SVector [q, 0.0] for q in LinRange(0.0, 3.0 * kF, Qsize)] end function integrand(config) if config.curr != 1 error("impossible") end para = config.para T, K, Ext = config.var[1], config.var[2], config.var[3] k = K[1] Tin, Tout = T[1], T[2] extidx = Ext[1] q = para.extQ[extidx] # external momentum kq = k + q τ = (Tout - Tin) ω1 = (dot(k, k) - kF^2) / (2me) g1 = Spectral.kernelFermiT(τ, ω1, β) ω2 = (dot(kq, kq) - kF^2) / (2me) g2 = Spectral.kernelFermiT(-τ, ω2, β) phase = 1.0 / (2π)^para.dim return g1 * g2 * spin * phase * cos(2π * para.n * τ / β) / β end function measure(config) obs = config.observable factor = 1.0 / config.reweight[config.curr] extidx = config.var[3][1] weight = integrand(config) obs[extidx] += weight / abs(weight) * factor end function run(steps) para = Para() @unpack dim, extQ, Qsize = para T = MCIntegration.Tau(β, β / 2.0) K = MCIntegration.FermiK(dim, kF, 0.2 * kF, 10.0 * kF) Ext = MCIntegration.Discrete(1, length(extQ)) # external variable is specified dof = [[2, 1, 1],] # degrees of freedom of the normalization diagram and the bubble obs = zeros(Float64, Qsize) # observable for the normalization diagram and the bubble config = MCIntegration.Configuration(steps, (T, K, Ext), dof, obs; para=para) avg, std = MCIntegration.sample(config, integrand, measure; print=0, Nblock=16) # @profview MonteCarlo.sample(config, integrand, measure; print=0, Nblock=1) # sleep(100) if isnothing(avg) == false @unpack n, extQ = Para() for (idx, q) in enumerate(extQ) q = q[1] p = Polarization.Polarization0_ZeroTemp(q, para.n, basic) * spin @printf("%10.6f %10.6f ± %10.6f %10.6f\n", q / basic.kF, avg[idx], std[idx], p) end end end run(Steps) # @time run(Steps)
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
3338
""" In this demo, we analysis the contribution of the exchange KO interaction to the Landau parameters """ using ElectronGas, Parameters using Lehmann, GreenFunc, CompositeGrids const rs = 7.0 const beta = 25.0 const mass2 = 1e-8 const dim = 3 const z = 1.0 Fp = -1.5 Fm = -0.0 # U = -0.456 U = 0.0 Cp, Cm = U / 2, -U / 2 massratio = 1.0 para = Parameter.rydbergUnit(1 / beta, rs, dim; Λs = mass2) println(para) const kF = para.kF const EF = para.EF const β = para.β const spin = para.spin const NF = para.NF * massratio println(NF) function exchange_interaction(Fp, Fm, massratio, Cp = 0.0, Cm = 0.0) θgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, π], [0.0, π], 16, 0.001, 16) qs = [2 * kF * sin(θ / 2) for θ in θgrid.grid] Wp = zeros(Float64, length(qs)) Wm = zeros(Float64, length(qs)) for (qi, q) in enumerate(qs) Wp[qi], Wm[qi] = Interaction.KO_total(q, 0, para; pifunc = Polarization.Polarization0_ZeroTemp_Quasiparticle, landaufunc = Interaction.landauParameterConst, Vinv_Bare = Interaction.coulombinv, counter_term = Interaction.countertermConst, Fs = -Fp, Fa = -Fm, Cs = -Cp, Ca = -Cm, massratio = massratio) # instantS[qi] = Interaction.coulombinv(q, para)[1] # println(q, " -> ", Wp[qi] * NF, ", ", Wm[qi] * NF) end Wp *= -NF * z^2 # additional minus sign because the interaction is exchanged Wm *= -NF * z^2 return Wp, Wm, θgrid end function Legrendre(l, func, θgrid) if l == 0 return Interp.integrate1D(func .* sin.(θgrid.grid), θgrid) / 2 elseif l == 1 return Interp.integrate1D(func .* cos.(θgrid.grid) .* sin.(θgrid.grid), θgrid) / 2 else error("not implemented!") end end # exchange interaction (Ws + Wa \sigma\sigma)_ex to a direct interaction Ws'+Wa' \sigma\sigma # # exchange S/A interaction projected to the spin-symmetric and antisymmetric parts function exchange2direct(Wse, Wae) Ws = (Wse + 3 * Wae) / 2 Wa = (Wse - Wae) / 2 return Ws, Wa end function projected_exchange_interaction(l, Fp, Fm, massratio, verbose = 1) println("l=$l:") Wse, Wae, θgrid = exchange_interaction(Fp, Fm, massratio) Wse0 = Legrendre(l, Wse, θgrid) Wae0 = Legrendre(l, Wae, θgrid) verbose > 1 && println("Wse_l=$l=", Wse0) verbose > 1 && println("Wae_l=$l=", Wae0) Ws0, Wa0 = exchange2direct(Wse0, Wae0) verbose > 0 && println("Ws_l=$l=", Ws0) verbose > 0 && println("Wa_l=$l=", Wa0) return Ws0, Wa0 end Ws0, Wa0 = projected_exchange_interaction(0, Fp, Fm, massratio) Wsc, Wac = exchange2direct(Fp, Fm) println(Ws0 + Wsc) println(Wa0 + Wac) # projected_exchange_interaction(1, Fp, Fm, massratio) exit(0) Fs, Fa = Fp, Fm mix = 0.2 for i = 1:100 println("iteration: $i") global Fs, Fa nFs, nFa = projected_exchange_interaction(0, Fs, Fa, massratio) Fs = Fs * (1 - mix) + 2 * nFs * mix Fa = Fa * (1 - mix) + nFa * mix Fa = 0.0 end println("Fs = ", Fs) println("Fa = ", Fa) # Ws1 = Interp.integrate1D(Ws .* cos.(θgrid.grid) .* sin.(θgrid.grid), θgrid) / 2 # Wa1 = Interp.integrate1D(Wa .* cos.(θgrid.grid) .* sin.(θgrid.grid), θgrid) / 2 # println("l=1:") # println("F1+=", Ws1) # println("F1-=", Wa1) # println("m^*/m = ", 1 + Ws1) # println(sqrt(4π * para.e0^2 * para.NF) / para.kF)
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
7832
""" Calculate gap-function equation """ using LinearAlgebra using ElectronGas using ElectronGas.GreenFunc using ElectronGas.Parameters using ElectronGas.Lehmann using ElectronGas.CompositeGrids using ElectronGas.Convention const dim = 2 # const beta, rs = 1e5, 1.5 function G02wrapped(fdlr, kgrid, param) # return G0(K)G0(-K) @unpack me, kF, β, μ = param green_dyn = zeros(Float64, (kgrid.size, fdlr.size)) for (ki, k) in enumerate(kgrid) for (ni, n) in enumerate(fdlr.n) ω = k^2 / 2 / me - μ green_dyn[ki, ni] = 1 / ( ((2n + 1) * π / β)^2 + (ω)^2 ) end end return green_dyn end function G2wrapped(fdlr, kgrid, param, Σ::GreenFunc.Green2DLR) # return G(K)G(-K) @unpack me, kF, β, μ = param Σ_freq = GreenFunc.toMatFreq(Σ, fdlr.n) Σ_shift = real(GreenFunc.dynamic(Σ_freq, π / β, kF, 1, 1) + GreenFunc.instant(Σ_freq, kF, 1, 1)) green_dyn = zeros(Float64, (kgrid.size, fdlr.size)) for (ki, k) in enumerate(kgrid) for (ni, n) in enumerate(fdlr.n) ω = k^2 / 2 / me - μ ΣR, ΣI = real(Σ_freq.dynamic[1, 1, ki, ni] + Σ_freq.instant[1, 1, ki] - Σ_shift), imag(Σ_freq.dynamic[1, 1, ki, ni]) green_dyn[ki, ni] = 1 / ( ((2n + 1) * π / β - ΣI)^2 + (ω + ΣR)^2 ) end end return green_dyn end function ΔFinit(fdlr, kgrid) delta = zeros(Float64, (kgrid.size, fdlr.size)) F = zeros(Float64, (kgrid.size, fdlr.size)) delta0 = zeros(Float64, kgrid.size) for (ki, k) in enumerate(kgrid) delta0[ki] = 1.0 for (τi, τ) in enumerate(fdlr.τ) delta[ki, τi] = 1.0 end end return delta, delta0, F end function dotΔ(fdlr, kgrid, Δ, Δ0, Δ2=Δ, Δ02=Δ0) # kF_label = searchsortedfirst(kgrid.grid, param.kF) # return Δ0[kF_label] + real(Lehmann.tau2matfreq(fdlr, view(Δ, kF_label, :), fdlr.n))[1] # return (dot(Δ, Δ2) + dot(Δ0, Δ02)) return (dot(Δ, Δ2)) end function calcF!(F, fdlr, kgrid, Δ, Δ0, G2) Δ_freq = real(Lehmann.tau2matfreq(fdlr, Δ, fdlr.n; axis=2)) for (ki, k) in enumerate(kgrid.grid) for (ni, n) in enumerate(fdlr.n) F[ki, ni] = (Δ_freq[ki, ni] + Δ0[ki]) * G2[ki, ni] end end end function calcΔ!(Δ, Δ0, fdlr, kgrid, qgrids, F, kernel, kernel_bare) F_tau = real(Lehmann.matfreq2tau(fdlr, F, fdlr.τ; axis=2)) F_ins = -real(tau2tau(fdlr, F_tau, [fdlr.β,]; axis=2))[:, 1] for (ki, k) in enumerate(kgrid.grid) for (τi, τ) in enumerate(fdlr.τ) Fk = CompositeGrids.Interp.interp1DGrid(view(F_tau, :, τi), kgrid, qgrids[ki].grid) integrand = view(kernel, ki, 1:qgrids[ki].size, τi) .* Fk Δ[ki, τi] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) ./ (-4 * π * π) if τi == 1 Fk = CompositeGrids.Interp.interp1DGrid(F_ins, kgrid, qgrids[ki].grid) integrand = view(kernel_bare, ki, 1:qgrids[ki].size) .* Fk Δ0[ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) ./ (-4 * π * π) end end end end function calcΔ_2d!(Δ, Δ0, fdlr, kgrid, qgrids, F, kernel, kernel_bare) F_tau = real(Lehmann.matfreq2tau(fdlr, F, fdlr.τ; axis=2)) F_ins = -real(tau2tau(fdlr, F_tau, [fdlr.β,]; axis=2))[:, 1] for (ki, k) in enumerate(kgrid.grid) for (τi, τ) in enumerate(fdlr.τ) Fk = CompositeGrids.Interp.interp1DGrid(view(F_tau, :, τi), kgrid, qgrids[ki].grid) integrand = view(kernel, ki, 1:qgrids[ki].size, τi) .* Fk .* k Δ[ki, τi] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) ./ (-4 * π * π) if τi == 1 Fk = CompositeGrids.Interp.interp1DGrid(F_ins, kgrid, qgrids[ki].grid) integrand = view(kernel_bare, ki, 1:qgrids[ki].size) .* Fk .* k Δ0[ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) ./ (-4 * π * π) end end end end function gapIteration(param, fdlr, kgrid, qgrids, kernel, kernel_bare, G2; Nstep=1e2, rtol=1e-6, shift=2.0) @unpack dim = param Δ, Δ0, F = ΔFinit(fdlr, kgrid) delta = zeros(Float64, (kgrid.size, fdlr.size)) delta0 = zeros(Float64, (kgrid.size)) n = 0 lamu, lamu0 = 1.0, 2.0 err = 1.0 while (n < Nstep && err > rtol) calcF!(F, fdlr, kgrid, Δ, Δ0, G2) n = n + 1 delta = copy(Δ) delta0 = copy(Δ0) if dim == 3 calcΔ!(Δ, Δ0, fdlr, kgrid, qgrids, F, kernel, kernel_bare) elseif dim == 2 calcΔ_2d!(Δ, Δ0, fdlr, kgrid, qgrids, F, kernel, kernel_bare) end lamu = dotΔ(fdlr, kgrid, Δ, Δ0, delta, delta0) # dotΔ(fdlr, kgrid, Δ, Δ0, Δ2 = Δ, Δ02 = Δ0) Δ0 = Δ0 .+ shift .* delta0 Δ = Δ .+ shift .* delta #modulus = Normalization(delta_0_new, delta_0_new, kgrid) modulus = sqrt(dotΔ(fdlr, kgrid, Δ, Δ0)) Δ = Δ ./ modulus Δ0 = Δ0 ./ modulus err = abs(lamu - lamu0) / abs(lamu + EPS) lamu0 = lamu # println(lamu) end return lamu, Δ, Δ0, F end # if abspath(PROGRAM_FILE) == @__FILE__ function gapfunction(beta, rs, channel::Int, dim::Int, sigmatype) #--- parameters --- param = Parameter.defaultUnit(1 / beta, rs, dim) # Euv, rtol = 100 * param.EF, 1e-11 # maxK, minK = 20param.kF, 1e-8param.kF # Nk, order = 12, 10 Euv, rtol = 100 * param.EF, 1e-10 maxK, minK = 10param.kF, 1e-7param.kF Nk, order = 8, 8 int_type = :rpa # print(param) #--- prepare kernel --- if dim == 3 @time W = LegendreInteraction.DCKernel0(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, channel=channel) elseif dim == 2 @time W = LegendreInteraction.DCKernel_2d(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, channel=channel) else error("No support for $dim dimension!") end fdlr = Lehmann.DLRGrid(Euv, param.β, rtol, true, :pha) bdlr = W.dlrGrid kgrid = W.kgrid qgrids = W.qgrids kernel_bare = W.kernel_bare kernel_freq = W.kernel kernel = real(Lehmann.matfreq2tau(bdlr, kernel_freq, fdlr.τ, bdlr.n; axis=3)) kF_label = searchsortedfirst(kgrid.grid, param.kF) qF_label = searchsortedfirst(qgrids[kF_label].grid, param.kF) println("static kernel at (kF, kF):$(kernel_bare[kF_label, qF_label])") # println("dynamic kernel at (kF, kF):") # println(view(kernel_freq, kF_label, qF_label, :)) #--- prepare Σ --- if sigmatype == :g0w0 Σ = SelfEnergy.G0W0(param, Euv, rtol, Nk, maxK, minK, order, int_type) end #--- prepare G2 --- if sigmatype == :none G2 = G02wrapped(fdlr, kgrid, param) elseif sigmatype == :g0w0 G2 = G2wrapped(fdlr, kgrid, param, Σ) end # println("G2 at kF:") # println(view(G2, kF_label, :)) lamu, Δ, Δ0, F = gapIteration(param, fdlr, kgrid, qgrids, kernel, kernel_bare, G2; shift=4.0) println("beta = $beta, rs = $rs") println("channel = $channel") println("lamu = $lamu") Δ_freq = real(Lehmann.tau2matfreq(fdlr, Δ, fdlr.n; axis=2)) println(fdlr.ωn ./ param.EF) println(view(Δ_freq, kF_label, :)) # println(view(F, kF_label, :)) end if abspath(PROGRAM_FILE) == @__FILE__ # sigmatype = :none sigmatype = :g0w0 rs = 2.0 # rs = 0.5 channel = 0 # blist = [1e2, 1e3, 1e4, 1e5, 2e5] blist = [5e5] # blist = [1e2, 1e3, 5e3, 1e4] for (ind, beta) in enumerate(blist) gapfunction(beta, rs, channel, dim, sigmatype) end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
3580
# global constant e0 and mass2 is expected """ linear2D(data, xgrid, ygrid, x, y) linear interpolation of data(x, y) #Arguments: - xgrid: one-dimensional grid of x - ygrid: one-dimensional grid of y - data: two-dimensional array of data - x: x - y: y """ @inline function linear2D(data, xgrid, ygrid, x, y) xarray, yarray = xgrid.grid, ygrid.grid xi0, xi1, yi0, yi1 = 0, 0, 0, 0 if (x <= xarray[firstindex(xgrid)]) xi0 = 1 xi1 = 2 elseif (x >= xarray[lastindex(xgrid)]) xi0 = lastindex(xgrid) - 1 xi1 = xi0 + 1 else xi0 = floor(xgrid, x) xi1 = xi0 + 1 end if (y <= yarray[firstindex(ygrid)]) yi0 = 1 yi1 = 2 elseif (y >= yarray[lastindex(ygrid)]) yi0 = lastindex(ygrid) - 1 yi1 = yi0 + 1 else yi0 = floor(ygrid, y) yi1 = yi0 + 1 end dx0, dx1 = x - xarray[xi0], xarray[xi1] - x dy0, dy1 = y - yarray[yi0], yarray[yi1] - y d00, d01 = data[xi0, yi0], data[xi0, yi1] d10, d11 = data[xi1, yi0], data[xi1, yi1] g0 = data[xi0, yi0] * dx1 + data[xi1, yi0] * dx0 g1 = data[xi0, yi1] * dx1 + data[xi1, yi1] * dx0 gx = (g0 * dy1 + g1 * dy0) / (dx0 + dx1) / (dy0 + dy1) return gx end function lindhard(x) if (abs(x) < 1.0e-4) return 1.0 elseif (abs(x - 1.0) < 1.0e-4) return 0.5 else return 0.5 - (x^2 - 1) / 4.0 / x * log(abs((1 + x) / (1 - x))) end end function KOstatic(Fp, Fm, cp, cm, mr, qgrid) fp = Fp / NF / mr fm = Fm / NF / mr cp = cp / NF / mr cm = cm / NF / mr Wp = similar(qgrid) Wm = similar(qgrid) for (qi, q) in enumerate(qgrid) Π = mr * NF * lindhard(q / 2 / kF) Wp[qi] = (4π * e0^2 + fp * q^2) / ((1 + fp * Π) * q^2 + 4π * e0^2 * Π) - fp Wm[qi] = fm / (1 + fm * Π) - fm # Wp[qi] = (4π * e0^2 + fp * q^2) / ((1 + fp * Π) * q^2 + 4π * e0^2 * Π) + cp # Wm[qi] = fm / (1 + fm * Π) + cm # Wp[qi] = (4π * e0^2 + fp * (q^2 + mass2)) / ((1 + fp * Π) * (q^2 + mass2) + 4π * e0^2 * Π) # Wm[qi] = fm / (1 + fm * Π) end return Wp, Wm end function interactionDynamic(para, qd, τIn, τOut, dim = 3) dτ = abs(τOut - τIn) kDiQ = sqrt(dot(qd, qd)) if dim == 3 vd = 4π * e0^2 / (kDiQ^2 + mass2) + fp elseif dim == 2 vd = 2π * e0^2 / √(kDiQ^2 + mass2) + fp end if kDiQ <= para.qgrid.grid[1] q = para.qgrid.grid[1] + 1.0e-6 wd = vd * linear2D(para.dW0, para.qgrid, para.τgrid, q, dτ) # the current interpolation vanishes at q=0, which needs to be corrected! else wd = vd * linear2D(para.dW0, para.qgrid, para.τgrid, kDiQ, dτ) # dynamic interaction, don't forget the singular factor vq end # return vd / β, wd #TODO introduce a fake tau variable to alleviate sign cancellation between the static and the dynamic interactions vd = 4π * e0^2 / (kDiQ^2 + mass2 + 4π * e0^2 * NF * lindhard(kDiQ / 2.0 / kF)) / β vd -= wd return vd, wd end function interactionStatic(para, qd, τIn, τOut) dτ = abs(τOut - τIn) kDiQ = sqrt(dot(qd, qd)) vd = 4π * e0^2 / (kDiQ^2 + mass2) / β return vd, 0.0 end function vertexDynamic(para, qd, qe, τIn, τOut) vd, wd = interactionDynamic(para, qd, τIn, τOut) ve, we = interactionDynamic(para, qe, τIn, τOut) return -vd, -wd, ve, we end function vertexStatic(para, qd, qe, τIn, τOut) vd, wd = interactionStatic(para, qd, τIn, τOut) ve, we = interactionStatic(para, qe, τIn, τOut) return -vd, -wd, ve, we end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
1436
module MeasureChi using ElectronGas using ElectronGas.GreenFunc using ElectronGas.CompositeGrids using DelimitedFiles export measure_chi function measure_chi(F_freq::GreenFunc.MeshArray) F_dlr = F_freq |> to_dlr F_ins = real(dlr_to_imtime(F_dlr, [F_freq.mesh[1].representation.β,])) * (-1) kgrid = F_ins.mesh[2] integrand = view(F_ins, 1, :) return real(CompositeGrids.Interp.integrate1D(integrand, kgrid)) end function measure_chi(dim, θ, rs; kwargs...) param = Parameter.rydbergUnit(θ, rs, dim) channel = 0 lamu, R_freq, F_freq = BSeq.linearResponse(param, channel ; kwargs...) result = measure_chi(F_freq) println("1/chi=", 1 / result) data = [1 / θ 1 / result lamu channel rs] dir = "./run/" fname = "gap_chi_rs$(rs)_l$(channel).txt" open(dir * fname, "a+") do io writedlm(io, data, ' ') end return 1 / result end end using Test using .MeasureChi @testset "measure chi" begin # println(measure_chi(3, 1e-2, 2.0)) dim = 3 rs = 7.0 num = 20 # beta = [6.25 * 2^i for i in LinRange(0, num - 1, num)] # beta = [2000, 2200.0, 2229.78,] beta = [3200,] # num = 18 # beta = [6.25 * sqrt(2)^i for i in LinRange(0, num - 1, num)] # chi = [measure_chi(dim, 1 / b, rs; sigmatype=:g0w0) for b in beta] chi = [measure_chi(dim, 1 / b, rs; atol=1e-10, rtol=1e-10, verbose=true) for b in beta] println(chi) end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
1066
# We work with Rydberg units, length scale Bohr radius a_0, energy scale: Ry using StaticArrays ###### constants ########### const e0 = sqrt(2) # electric charge const me = 0.5 # electron mass const dim = 3 # dimension (D=2 or 3, doesn't work for other D!!!) const spin = 2 # number of spins const rs = 1.0 const kF = (dim == 3) ? (9π / (2spin))^(1 / 3) / rs : sqrt(4 / spin) / rs const EF = kF^2 / (2me) const beta = 1000 const β = beta / EF const mass2 = 1e-6 const NF = (dim == 3) ? spin * me * kF / 2 / π^2 : spin * me / 2 / π const qTF = sqrt(4π * e0^2 * NF) const fp = -0.0 const fm = -0.0 # const Weight = SVector{2,Float64} const INL, OUTL, INR, OUTR = 1, 2, 3, 4 const DI, EX = 1, 2 # const Nf = (D==3) ? mutable struct Weight <: FieldVector{2,Float64} d::Float64 e::Float64 Weight() = new(0.0, 0.0) Weight(d, e) = new(d, e) end const Base.zero(::Type{Weight}) = Weight(0.0, 0.0) const Base.abs(w::Weight) = abs(w.d) + abs(w.e) # define abs(Weight) println("rs=$rs, β=$β, kF=$kF, EF=$EF, mass2=$mass2, NF=$NF, qTF/kF=$(qTF/kF)")
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
2769
""" Check how the sigma function changes with the external momentum within the G0W0 approximation. Both the z-factor and band mass ratio are calculated. It is found that that the plasma approximation for the polarization didn't change the result much. The locality of the z-factor and band mass seems to be protected by the condition that ω_p >> E_F """ using ElectronGas using Plots using LaTeXStrings using GreenFunc rs = 5.0 beta = 1000.0 mass2 = 1e-6 para = Parameter.rydbergUnit(1.0 / beta, rs, 3; Λs=mass2) # create the benchmark self-energy with the standard polarization sigma0 = SelfEnergy.G0W0(para; pifunc=Polarization.Polarization0_3dZeroTemp); kgrid = [k for k in sigma0.spaceGrid.grid if k < para.kF * 2] z0 = [SelfEnergy.zfactor(para, sigma0; kamp=k)[1] for k in kgrid] mass0 = [SelfEnergy.bandmassratio(para, sigma0; kamp=k)[1] for k in kgrid] factorList = [0.1875, 0.75, 3.0, 18.74, 300.0, 30000.0] # factorList = [1.0, 3.0] z = zeros(length(factorList), length(kgrid)) mass = zeros(length(factorList), length(kgrid)) plasmafreq(factor) = round(1 / sqrt(factor / 3), sigdigits=3) # fake plasma freq vesus physical one ef(factor) = round(plasmafreq(factor) * para.ωp / para.EF, sigdigits=3) # fake plasma freq vesus physical EF # plasmafreq(factor) = round(factor, sigdigits=3) Threads.@threads for fi in eachindex(factorList) factor = factorList[fi] println("factor $factor") sigma = SelfEnergy.G0W0(para, Euv=1000.0 * para.EF, Nk=12, order=8; pifunc=Polarization.Polarization0_3dZeroTemp_Plasma, factor=factor) # sigma = SelfEnergy.G0W0(para; pifunc=Polarization.Polarization0_3dZeroTemp_Plasma, factor=factor) for (i, k) in enumerate(kgrid) z[fi, i] = SelfEnergy.zfactor(para, sigma; kamp=k)[1] # mass[fi, i] = SelfEnergy.bandmassratio(para, sigma; kamp=k) mass[fi, i] = SelfEnergy.bandmassratio(para, sigma; kamp=k)[1] # mass[fi, i] = sigma.dynamic[] end end let p = plot(xlabel=L"$k/k_F$", ylabel=L"$z_k$", legend=:bottomright) plot!(p, kgrid ./ para.kF, z0, label="physical") for (fi, factor) in enumerate(factorList[1:end-1]) plot!(p, kgrid ./ para.kF, z[fi, :], label=L"$\tilde{\omega}_p = %$(plasmafreq(factor))\omega_p = %$(ef(factor))E_F$") end savefig(p, "sigma_locality_z.pdf") display(p) end let p = plot(xlabel=L"$k/k_F$", ylabel=L"$m^*_k/m_0$", legend=:topright, xlim=[0.1, kgrid[end] / para.kF], ylim=[0.75, 1.401]) plot!(p, kgrid ./ para.kF, mass0, label="physical") for (fi, factor) in enumerate(factorList[1:end-1]) plot!(p, kgrid ./ para.kF, mass[fi, :], label=L"$\tilde{\omega}_p = %$(plasmafreq(factor))\omega_p = %$(ef(factor))E_F$") end savefig(p, "sigma_locality_massratio.pdf") display(p) end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
2006
# Self-energy for spin-fermion model using ElectronGas using Test, Printf, DelimitedFiles using Gaston, LaTeXStrings bexp = 3 ExtQ = 0 dim = 2 beta, rs = 10^bexp, 1.0 ga = 1.0 param = Interaction.Parameter.rydbergUnit(1 / beta, rs, dim) Λa = param.Λa + Polarization.Polarization0_ZeroTemp(0.0, 0, param) * param.spin * ga * (-param.e0a^2) / param.ϵ0 println(Λa) param = Parameter.Para(param, gs = 0.0, ga = ga, Λa = Λa) function sigma(param) Euv, rtol = 100 * param.EF, 1e-10 Nk, order, minK = 8, 8, 1e-7 # Nk, order, minK = 11, 4, 1e-8 Σ = SelfEnergy.G0W0(param, Euv, rtol, Nk, 10 * param.kF, minK * param.kF, order, :rpa) Σ = SelfEnergy.GreenFunc.toMatFreq(Σ) kgrid = Σ.spaceGrid println(kgrid) kF = kgrid.panel[3] kF_label = searchsortedfirst(kgrid.grid, kF) println(kF_label) ωgrid = Σ.dlrGrid ΣR = real(Σ.dynamic) ΣI = imag(Σ.dynamic) println(real(Σ.instant[1, 1, :])) println(ΣR[1, 1, kF_label, :]) label = 1 print([ωgrid.n ωgrid.ωn ΣR[1, 1, label, :] ΣI[1, 1, label, :]]) # open("./plot/sigma_b1e$(bexp)_q$(ExtQ)kf_m0.txt", "w") do io # writedlm(io, [ωgrid.n ωgrid.ωn ΣR[1, 1, label, :] ΣI[1, 1, label, :]]) # end end if abspath(PROGRAM_FILE) == @__FILE__ sigma(param) data = readdlm("./plot/sigma_b1e$(bexp)_q$(ExtQ)kf_m0.txt", '\t', Float64, '\n') # using Gaston # x = ωgrid.ωn / param.EF # y = ΣI[1, 1, kF_label, :] x = data[:, 2] / param.EF y = -data[:, end] plot(x, y, curveconf = "notit w lp lw 1 lc '#08F7FE'", Axes(xrange = (0, 0.1), # yrange = (-4, 1.2), ylabel = "'-Im Σ'", # ylabel = "'f_{xc} N_F (q/ω_n)^2'", xlabel = "'ω_n/E_F'", key = "t l", title = "'beta=$beta, r_s=$rs'") ) x = 0:1e-2:2 y = x .^ (2 / 3) .* 0.16 plot!(x, y, curveconf = "tit 'ω_n^{2/3}'") save(term = "pdf", output = "./plot/SigmaIm_b1e$(bexp)_rs$(rs)_q$(ExtQ)kf.pdf", linewidth = 1) end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
17697
""" Bethe-Slapter-type equation solver and the application to Cooper-pair linear response approach. """ module BSeq using ..Parameter, ..Convention, ..LegendreInteraction using ..Parameters, ..GreenFunc, ..Lehmann, ..CompositeGrids using ..SelfEnergy const freq_sep = 0.01 """ function initFR(Euv, rtol, sgrid, param) Initalize the Bethe-Slapter amplitude `F` in imaginary-frequency space and `R ≡ F(GG)⁻¹` in imaginary-time space. # Arguments: - `Euv`: the UV energy scale of the spectral density. parameter for DLR grids. - `rtol`: tolerance absolute error. parameter for DLR grids. - `sgrid`: momentum grid of F and R - `param`: parameters of ElectronGas. # Return - ``F(\\omega_n, k)=0`` as a `GreenFunc.MeshArray` - the dynamical part of `R` in the imaginary-time space as a `GreenFunc.MeshArray`. In the imaginary-frequency space, ```math R(\\omega_n, k) = \\frac{1}{\\Omega_c^2+e^2}\\left(1- \\frac{2\\omega_n^2}{\\omega_n^2+\\Omega_c^2} \\right) ``` where ``e=k^2/(2m)-\\mu`` and ``\\Omega_c =0.01``. - the instant part of `R` as a `GreenFunc.MeshArray`, ``R_{\\mathrm{ins}}(k)=0``. """ function initFR(Euv, rtol, sgrid, param) @unpack β, me, μ = param Ω_c = freq_sep wn_mesh = GreenFunc.ImFreq(β, FERMION; Euv=Euv, rtol=rtol, symmetry=:pha) R_freq = GreenFunc.MeshArray(wn_mesh, sgrid; dtype=Float64) F_freq = similar(R_freq) for ind in eachindex(R_freq) ni, ki = ind[1], ind[2] ωn, k = wn_mesh[ni], sgrid[ki] e = k^2 / 2 / me - μ R_freq[ni, ki] = (1.0 - 2.0 * ωn^2 / (ωn^2 + Ω_c^2)) / (Ω_c^2 + e^2) end R_imt = real(R_freq |> to_dlr |> to_imtime) R_ins = GreenFunc.MeshArray([1], sgrid; dtype=Float64, data=zeros(1, sgrid.size)) return F_freq, R_imt, R_ins end """ function calcF!(F::GreenFunc.MeshArray, R::GreenFunc.MeshArray, R_ins::GreenFunc.MeshArray, G2::GreenFunc.MeshArray) Calculation of the Bethe-Slapter amplitude `F` from the product of single-particle Green's function `G2` and the dynamical and instant parts of `R`, `R_ins`. Compute in frequency space to avoid \\tau integration. ```math F(\\omega_n, k) = G^{(2)}(\\omega_n, k) [R(\\omega_n, k)+R_{\\mathrm{ins}}(k)] ``` """ function calcF!(F::GreenFunc.MeshArray, R::GreenFunc.MeshArray, R_ins::GreenFunc.MeshArray, G2::GreenFunc.MeshArray) R_freq = R |> to_dlr |> to_imfreq # algebraic in frequency space for ind in eachindex(F) F[ind] = real(R_freq[ind] + R_ins[1, ind[2]]) * G2[ind] end end """ function calcR!(F::GreenFunc.MeshArray, R::GreenFunc.MeshArray, R_ins::GreenFunc.MeshArray, source::Union{Nothing,GreenFunc.MeshArray}, kernel, kernel_ins, qgrids::Vector{CompositeGrid.Composite}) Calculate ``kR(\\tau, k)`` in three dimensions by given `pF(\\tau, p)` and `kernel`. Compute in imaginary time space to aviod frequency convolution. ```math kR(\\tau, k) = k\\eta(\\tau, k) - \\int \\frac{dp}{4\\pi^2} H(\\tau,k,p) pF(\\tau,p), ``` where ``H(\\tau,k,p)\\equiv kp W(\\tau,k,p)`` is the helper function of interaction (see [Legendre Decomposition of Interaction](https://numericaleft.github.io/ElectronGas.jl/dev/manual/legendreinteraction/)) and the kernel argument. The dynamical `source` ``k\\eta(\\tau, k)`` will be added if it is given as `GreenFunc.MeshArray`. """ function calcR!(F::GreenFunc.MeshArray, R::GreenFunc.MeshArray, R_ins::GreenFunc.MeshArray, source::Union{Nothing,GreenFunc.MeshArray}, kernel, kernel_ins, qgrids::Vector{CompositeGrid.Composite}) kgrid = F.mesh[2] F_dlr = F |> to_dlr # switch to τ space F_imt = real(F_dlr |> to_imtime) F_ins = real(dlr_to_imtime(F_dlr, [F.mesh[1].representation.β,])) * (-1) for ind in eachindex(R) # for each τ, k, integrate over q τi, ki = ind[1], ind[2] # interpolate F to q grid of given k Fq = CompositeGrids.Interp.interp1DGrid(view(F_imt, τi, :), kgrid, qgrids[ki].grid) integrand = view(kernel, ki, 1:qgrids[ki].size, τi) .* Fq R[τi, ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) ./ (-4 * π * π) if τi == 1 # same for instant part Fq = CompositeGrids.Interp.interp1DGrid(view(F_ins, 1, :), kgrid, qgrids[ki].grid) integrand = view(kernel_ins, ki, 1:qgrids[ki].size) .* Fq R_ins[1, ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) ./ (-4 * π * π) end end !(source isa Nothing) && (R += source) end """ function calcR_2d!(F::GreenFunc.MeshArray, R::GreenFunc.MeshArray, R_ins::GreenFunc.MeshArray, source::Union{Nothing,GreenFunc.MeshArray}, kernel, kernel_ins, qgrids::Vector{CompositeGrid.Composite}) Calculate ``kR(\\tau, k)`` in two dimensions by given `pF(p)` and `kernel` Compute in imaginary time space to aviod frequency convolution. ```math kR(\\tau, k) = k\\eta(\\tau, k) - \\int \\frac{pdp}{4\\pi^2} W(\\tau,k,p) pF(\\tau,p), ``` where ``W`` is the interaction and the kernel argument. The dynamical `source` ``k\\eta(\\tau, k)`` will be added if it is given as `GreenFunc.MeshArray`. """ function calcR_2d!(F::GreenFunc.MeshArray, R::GreenFunc.MeshArray, R_ins::GreenFunc.MeshArray, source::Union{Nothing,GreenFunc.MeshArray}, kernel, kernel_ins, qgrids::Vector{CompositeGrid.Composite}) # similar to 3d kgrid = F.mesh[2] F_dlr = F |> to_dlr F_imt = real(F_dlr |> to_imtime) F_ins = real(dlr_to_imtime(F_dlr, [F.mesh[1].representation.β,])) * (-1) for ind in eachindex(R) τi, ki = ind[1], ind[2] k = R.mesh[2][ki] Fq = CompositeGrids.Interp.interp1DGrid(view(F_imt, τi, :), kgrid, qgrids[ki].grid) integrand = view(kernel, ki, 1:qgrids[ki].size, τi) .* Fq .* k R[τi, ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) ./ (-4 * π * π) if τi == 1 Fq = CompositeGrids.Interp.interp1DGrid(view(F_ins, 1, :), kgrid, qgrids[ki].grid) integrand = view(kernel_ins, ki, 1:qgrids[ki].size) .* Fq .* k R_ins[1, ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) ./ (-4 * π * π) end end !(source isa Nothing) && (R += source) end """ function G02wrapped(Euv, rtol, sgrid, param) Returns the product of two bare single-particle Green's function. ```math G_0^{(2)}(\\omega_n, k) = 1/(\\omega_n^2+\\omega^2) ``` where ``\\omega= k^2/(2m)-\\mu``. """ function G02wrapped(Euv, rtol, sgrid, param) @unpack me, β, μ = param wn_mesh = GreenFunc.ImFreq(β, FERMION; Euv=Euv, rtol=rtol, symmetry=:pha) green = GreenFunc.MeshArray(wn_mesh, sgrid; dtype=Float64) for ind in eachindex(green) ni, ki = ind[1], ind[2] ωn = wn_mesh[ni] ω = sgrid.grid[ki]^2 / 2 / me - μ green[ind] = 1 / (ωn^2 + ω^2) end return green end """ function G2wrapped(Σ::GreenFunc.MeshArray, Σ_ins::GreenFunc.MeshArray, param) Returns the product of two single-particle Green's function from given dynamical and instant parts of self-energy (`Σ` and `Σ_ins`). ```math G_0^{(2)}(\\omega_n, k) = 1/\\left([\\omega_n - \\mathrm{Im} \\Sigma(\\omega_n, k)]^2+ [\\omega+ \\mathrm{Re} \\Sigma(\\omega_n, k) - \\Sigma_{\\mathrm{shift}}]^2\\right) ``` where ``\\omega= k^2/(2m)-\\mu`` and ``\\Sigma_{\\mathrm{shift}}=\\mathrm{Re} \\Sigma(\\omega_0, k_F)``. """ function G2wrapped(Σ::GreenFunc.MeshArray, Σ_ins::GreenFunc.MeshArray, param) @unpack me, kF, β, μ = param Σ_freq = Σ |> to_dlr |> to_imfreq green = similar(Σ_freq) w0i_label = locate(Σ_freq.mesh[1], 0) kf_label = locate(Σ_freq.mesh[2], kF) Σ_shift = real(Σ_freq[w0i_label, kf_label] + Σ_ins[1, kf_label]) for ind in eachindex(green) ni, ki = ind[1], ind[2] ωn = green.mesh[1][ni] ω = green.mesh[2][ki]^2 / 2 / me - μ ΣR, ΣI = real(Σ_freq[ind] + Σ_ins[1, ki] - Σ_shift), imag(Σ_freq[ind]) green[ind] = 1 / ((ωn - ΣI)^2 + (ω + ΣR)^2) end return green end """ function BSeq_solver(param, G2::GreenFunc.MeshArray, kernel, kernel_ins, qgrids::Vector{CompositeGrid.Composite}, Euv; Ntherm=120, rtol=1e-10, α=0.7, source::Union{Nothing,GreenFunc.MeshArray}=nothing, source_ins::GreenFunc.MeshArray=GreenFunc.MeshArray([1], G2.mesh[2]; dtype=Float64, data=ones(1, G2.mesh[2].size)) ) Bethe-Slapter equation solver by self-consistent iterations. ```math R(\\omega_n, k) = \\eta(\\omega_n, k) - \\frac{1}{\\beta} \\sum_m \\frac{d^dp}{(2\\pi)^d} \\Gamma(\\omega_n,k;\\omega_m,p) G^{(2)}(\\omega_m,p)R(\\omega_m,p) , ``` where ``\\eta(\\omega_n, k)`` is the sourced term, ``\\Gamma(k,\\omega_n;p,\\omega_m)`` is the particle-particle four-point vertex with zero incoming momentum and frequency, and ``G^{(2)}(p,\\omega_m)`` is the product of two single-particle Green's function. # Arguments - `param`: parameters of ElectronGas. - `G2`: product of two single-particle Green's function (::GreenFunc.MeshArray). - `kernel`: dynamical kernel of the Legendre decomposed effective interaction. - `kernel_ins`: instant part of the the Legendre decomposed effective interaction. - `qgrids`: momentum grid of kernel (::Vector{CompositeGrid.Composite}). - `Euv`: the UV energy scale of the spectral density. - `Ntherm`: thermalization step. By defalut, `Ntherm=120`. - `rtol`: tolerance absolute error. By defalut, `rtol=1e-10`. - `α`: mixing parameter in the self-consistent iteration. By default, `α=0.7`. - `source`: dynamical part of sourced term in imaginary-time space. By default, `source=nothing`. - `source_ins`: instant part of sourced term. By default, `source_ins=1`. # Return - Inverse of low-energy linear response `1/R₀` (``R_0=R(\\omega_0, k_F)``) - Bethe-Slapter amplitude `F` in imaginary-frequency space ```math F(\\omega_m, p) = G^{(2)}(\\omega_m,p)R(\\omega_m,p) ``` - dynamical part of `R` in imaginary-time space - instant part of `R` in imaginary-time space """ function BSeq_solver(param, G2::GreenFunc.MeshArray, kernel, kernel_ins, qgrids::Vector{CompositeGrid.Composite}, Euv; Ntherm=30, rtol=1e-10, atol=1e-10, α=0.8, source::Union{Nothing,GreenFunc.MeshArray}=nothing, source_ins::GreenFunc.MeshArray=GreenFunc.MeshArray([1], G2.mesh[2]; dtype=Float64, data=ones(1, G2.mesh[2].size)), verbose=false, Ncheck=5) if verbose println("atol=$atol,rtol=$rtol") end @unpack dim, kF = param kgrid = G2.mesh[2] kF_label = locate(kgrid, kF) if !(source isa Nothing) @assert source.mesh[1] isa MeshGrids.ImTime "ImTime is expect for the dim = 1 source." for ni in eachindex(F_freq.mesh[1]) source[ni, :] .*= kgrid.grid end end source_ins[1, :] .*= kgrid.grid source0 = source_ins[1, kF_label] # Initalize F and R F_freq, R_imt, R_ins = initFR(Euv, G2.mesh[1].representation.rtol, kgrid, param) R0, R0_sum = 1.0, 0.0 dR0, dR0_sum = zeros(Float64, (kgrid.size)), zeros(Float64, (kgrid.size)) R_sum = zeros(Float64, (R_imt.mesh[1].representation.size, kgrid.size)) lamu, lamu0 = 0.0, 1.0 n = 0 # self-consistent iteration with mixing α # Note!: all quantites about R, F, and source in the `while` loop are multiplied by momentum k. while (true) n = n + 1 # switch between imtime and imfreq to avoid convolution # dlr Fourier transform is much faster than brutal force convolution # calculation from imtime R to imfreq F calcF!(F_freq, R_imt, R_ins, G2) # calculation from imfreq F to imtime R if dim == 3 calcR!(F_freq, R_imt, R_ins, source, kernel, kernel_ins, qgrids) elseif dim == 2 calcR_2d!(F_freq, R_imt, R_ins, source, kernel, kernel_ins, qgrids) else error("Not implemented for $dim dimensions.") end R_kF = real(dlr_to_imfreq(to_dlr(R_imt), [0])[1, kF_label] + R_ins[1, kF_label]) # split the low-energy part R0=R(ω₀,kF) and the remaining instant part dR0 for iterative calcualtions R0_sum = source0 + R_kF + R0_sum * α dR0_sum = view(R_ins, 1, :) + view(source_ins, 1, :) .- (source0 + R_kF) + dR0_sum .* α R0 = R0_sum * (1 - α) dR0 = dR0_sum .* (1 - α) R_ins[1, :] = dR0 .+ R0 # iterative calculation of the dynamical part R_sum = view(R_imt, :, :) + R_sum .* α R_imt[:, :] = R_sum .* (1 - α) @debug "R(ω0, kF) = $R_kF, 1/R0 = $(-1/R0) ($(-1/(kF + R_kF)))" # println("R(ω0, kF) = $R_kF, 1/R0 = $(-1/R0) ($(-1/(kF + R_kF)))") # record lamu=1/R0 if iterative step n > Ntherm if n > Ntherm && (n % Ncheck == 1) lamu = -1 / (1 + R_kF / kF) if lamu > 0 # this condition does not necessarily mean something wrong # it only indicates lamu is not converge to correct sign within Ntherm steps # normally α>0.8 guarantees convergence, then it means Ntherm is too small @warn ("α = $α or Ntherm=$Ntherm is too small!") end # err = abs(lamu - lamu0) # Exit the loop if the iteration converges isapprox(lamu, lamu0, rtol=rtol, atol=atol) && break lamu0 = lamu if verbose println("lamu=$lamu") end end end println("α = $α, iteration step: $n") lamu = -kF / R0 # calculate 1/R0 # calculate real physical quantites F and R for ni in eachindex(F_freq.mesh[1]) F_freq[ni, :] ./= kgrid.grid R_imt[ni, :] ./= kgrid.grid end R_ins[1, :] ./= kgrid.grid return lamu, F_freq, R_imt, R_ins end """ function linearResponse(param, channel::Int; Euv=100 * param.EF, rtol=1e-10, maxK=10param.kF, minK=1e-7param.kF, Nk=8, order=8, sigmatype=:none, int_type=:rpa, α=0.7) Implmentation of Cooper-pair linear response approach. # Arguments: - `param`: parameters of ElectronGas. - `channel::Int`: orbital angular channel (0: s-wave, 1: p-wave, ...) - `Euv`: the UV energy scale of the spectral density. By default, `Euv=100EF`. - `rtol`: tolerance absolute error. By defalut, `rtol=1e-10`. - `maxK`: maximum momentum of kgrid and qgrids. By default, `maxK=10kF`. - `minK`: minimum interval of panel kgrid and qgrids. By default, `minK=1e-7kF`. - `Nk`: number of grid points of panel kgrid and qgrids. By defalut, `Nk=8`. - `order`: number of grid points of subgrid of kgrid and qgrids. By defalut, `order=8`. - `sigmatype`: type of fermionic self-energy. (no self-energy :none, G0W0 approximation :g0w0) - `int_type`: type of effective interaction. By default, `int_type=:rpa`. - `α`: mixing parameter in the self-consistent iteration. By default, `α=0.7`. # Return: - Inverse of low-energy linear response `1/R₀` (``R_0=R(\\omega_0, k_F)``) - Linear response `R(ωₙ, k)`, which is calculated by the Bethe-Slapter-type equation ```math R(\\omega_n, k) = 1 - \\frac{1}{\\beta} \\sum_m \\int \\frac{d^dp}{(2\\pi)^d} \\Gamma(\\omega_n,k;\\omega_m,p) G^{(2)}(\\omega_m,p)R(\\omega_m,p) ``` where ``1`` is the default sourced term, ``\\Gamma(k,\\omega_n;p,\\omega_m)`` is the particle-particle four-point vertex with zero incoming momentum and frequency, and ``G^{(2)}(p,\\omega_m)`` is the product of two single-particle Green's function. """ function linearResponse(param, channel::Int; Euv=100 * param.EF, rtol=1e-10, atol=1e-10, maxK=10param.kF, minK=1e-7param.kF, Nk=8, order=8, sigmatype=:none, int_type=:rpa, α=0.8, verbose=false, Ntherm=30) @unpack dim, rs, β, kF = param if verbose println("atol=$atol,rtol=$rtol") end # prepare Legendre decomposed effective interaction if dim == 3 if channel == 0 @time W = LegendreInteraction.DCKernel0(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, channel=channel) else @time W = LegendreInteraction.DCKernel_old(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, channel=channel) end elseif dim == 2 @time W = LegendreInteraction.DCKernel_2d(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, channel=channel) else error("No support for $dim dimension!") end fdlr = Lehmann.DLRGrid(Euv, β, rtol, true, :pha) bdlr = W.dlrGrid kgrid = W.kgrid qgrids = W.qgrids # prepare kernel, interpolate into τ-space with fdlr.τ kernel_ins = W.kernel_bare kernel_freq = W.kernel kernel = real(Lehmann.matfreq2tau(bdlr, kernel_freq, fdlr.τ, bdlr.n; axis=3)) kF_label = locate(kgrid, kF) qF_label = locate(qgrids[kF_label], kF) println("static kernel at (kF, kF):$(kernel_ins[kF_label, qF_label])") # prepare G2 as sigmatype if sigmatype == :none G2 = G02wrapped(Euv, rtol, kgrid, param) elseif sigmatype == :g0w0 @unpack me, β, μ = param wn_mesh = GreenFunc.ImFreq(β, FERMION; Euv=Euv, rtol=rtol, symmetry=:pha) Σ, Σ_ins = SelfEnergy.G0W0(param, Euv, rtol, Nk, maxK, minK, order, int_type) # self energy should be converted to proper frequency grid Σ_dlr = Σ |> to_dlr Σ_wn = dlr_to_imfreq(Σ_dlr, wn_mesh) G2 = G2wrapped(Σ_wn, Σ_ins, param) end # calculate F, R by Bethe-Slapter iteration. lamu, F_freq, R_imt, R_ins = BSeq_solver(param, G2, kernel, kernel_ins, qgrids, Euv; rtol=rtol, α=α, atol=atol, verbose=verbose, Ntherm=Ntherm) println("1/R₀ = $lamu") R_freq = R_imt |> to_dlr |> to_imfreq # println(view(R_freq, :, kF_label)) return lamu, R_freq, F_freq end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
489
module ElectronGas using Parameters, GreenFunc, CompositeGrids, Lehmann, LegendrePolynomials # Write your package code here. include("twopoint.jl") export TwoPoint include("convention.jl") export Convention include("parameter.jl") export Parameter include("polarization.jl") export Polarization include("interaction.jl") export Interaction include("legendreinteraction.jl") export LegendreInteraction include("selfenergy.jl") export SelfEnergy include("BSeq.jl") export BSeq end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
484
""" Template of convention. Stores conventions that will not change for all purposes. """ module Convention # using StaticArrays # const Weight = SVector{2,Float64} # const Base.abs(w::Weight) = abs(w[1]) + abs(w[2]) # define abs(Weight) const INL, OUTL, INR, OUTR = 1, 2, 3, 4 const EPS = 1e-16 # export all conventions for n in names(@__MODULE__; all = true) if Base.isidentifier(n) && n ∉ (Symbol(@__MODULE__), :eval, :include) @eval export $n end end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
16669
module Interaction # using Parameters, GreenFunc # include(srcdir*"/parameter.jl") # using .Parameter # include(srcdir*"/convention.jl") # using .Convention # include(srcdir*"/polarization.jl") # using .Polarization using ..Parameter, ..Convention, ..Polarization using ..Parameters, ..CompositeGrids, ..GreenFunc export RPA, KO, RPAwrapped, KOwrapped, coulomb, coulomb_2d, landauParameterMoroni function inf_sum(q, n) # Calculate a series sum for Takada anzats # See Takada(doi:10.1103/PhysRevB.47.5202)(Eq.2.16). a = q * q sum = 1.0 i = 0 j = 1.0 k = 2.0 for i in 1:n sum = sum + a / j / k a = a * q * q j = j * (i + 1.0) k = k * (i + 2.0) end return 1.0 / sum / sum end """ function coulomb(q,param) Bare interaction in momentum space. Coulomb interaction if Λs=0, Yukawa otherwise. #Arguments: - q: momentum - param: other system parameters """ function coulomb(q, param) @unpack me, kF, rs, e0s, e0a, β, Λs, Λa, ϵ0, gs, ga = param if gs ≈ 0.0 Vs = 0.0 else if (q^2 + Λs) ≈ 0.0 Vs = Inf else Vs = e0s^2 / ϵ0 / (q^2 + Λs) * gs end end if ga ≈ 0.0 Va = 0.0 else if (q^2 + Λa) ≈ 0.0 Va = Inf else Va = e0a^2 / ϵ0 / (q^2 + Λa) * ga end end return Vs, Va end """ function coulomb_2d(q,param) Bare interaction in 2D momentum space. Coulomb interaction if Λs=0, Yukawa otherwise. #Arguments: - q: momentum - param: other system parameters """ function coulomb_2d(q, param) @unpack me, kF, rs, e0s, e0a, β, Λs, Λa, ϵ0, gs, ga = param if gs ≈ 0.0 Vs = 0.0 else if (q^2 + Λs) ≈ 0.0 Vs = Inf else Vs = e0s^2 / 2ϵ0 / √(q^2 + Λs) * gs end end if ga ≈ 0.0 Va = 0.0 else if (q^2 + Λa) ≈ 0.0 Va = Inf else # Va = e0a^2 / 2ϵ0 / √(q^2 + Λa) Va = e0a^2 / ϵ0 / (q^2 + Λa) * ga end end return Vs, Va end """ function coulombinv(q,param) Inverse of bare interaction in 3D momentum space. Coulomb interaction if Λs=0, Yukawa otherwise. #Arguments: - q: momentum - param: other system parameters """ function coulombinv(q, param) @unpack me, kF, rs, e0s, e0a, β, Λs, Λa, ϵ0, gs, ga = param if gs ≈ 0.0 Vinvs = Inf else Vinvs = ϵ0 * (q^2 + Λs) / e0s^2 / gs end if ga ≈ 0.0 Vinva = Inf else Vinva = ϵ0 * (q^2 + Λa) / e0a^2 / ga end return Vinvs, Vinva end """ function coulombinv_2d(q,param) Inverse of bare interaction in 2D momentum space. Coulomb interaction if Λs=0, Yukawa otherwise. #Arguments: - q: momentum - param: other system parameters """ function coulombinv_2d(q, param) @unpack me, kF, rs, e0s, e0a, β, Λs, Λa, ϵ0, gs, ga = param if gs ≈ 0.0 Vinvs = Inf else Vinvs = 2ϵ0 * √(q^2 + Λs) / e0s^2 / gs end if ga ≈ 0.0 Vinva = Inf else Vinva = ϵ0 * (q^2 + Λa) / e0a^2 / ga # Vinva = 2ϵ0 * √(q^2 + Λa) / e0a^2 end return Vinvs, Vinva end """ function bubbledyson(Vinv::Float64, F::Float64, Π::Float64) Return (V - F)^2 Π / (1 - (V - F)Π), which is the dynamic part of effective interaction. #Arguments: - Vinv: inverse bare interaction - F: Landau parameter - Π: polarization """ function bubbledyson(Vinv::Float64, F::Float64, Π::Float64) K = 0 if Vinv ≈ Inf if F ≈ 0 K = 0 else K = Π / (1.0 / (-F) - (Π)) * (-F) end else K = Π / (Vinv / (1 - F * Vinv) - (Π)) * (1 - F * Vinv) / Vinv end @assert !isnan(K) "nan at Vinv=$Vinv, F=$F, Π=$Π" return K end """ function bubbledysonreg(Vinv::Float64, F::Float64, Π::Float64) Return (V - F) Π / (1 - (V - F)Π), which is the dynamic part of effective interaction divided by (V - F). #Arguments: - Vinv: inverse bare interaction - F: Landau parameter - Π: polarization """ function bubbledysonreg(Vinv::Float64, F::Float64, Π::Float64) K = 0 if Vinv ≈ Inf if F ≈ 0 K = 0 else K = Π / (1.0 / (-F) - (Π)) end else K = Π / (Vinv / (1 - F * Vinv) - (Π)) end @assert !isnan(K) "nan at Vinv=$Vinv, F=$F, Π=$Π" return K end function bubblecorrection(q::Float64, n::Int, param; pifunc=Polarization0_ZeroTemp, landaufunc=landauParameterTakada, Vinv_Bare=coulombinv, regular=false, massratio=1.0, kwargs...) Fs::Float64, Fa::Float64 = landaufunc(q, n, param; massratio=massratio, kwargs...) Ks::Float64, Ka::Float64 = 0.0, 0.0 Vinvs::Float64, Vinva::Float64 = Vinv_Bare(q, param) @unpack spin = param if abs(q) < EPS q = EPS end Πs::Float64 = spin * pifunc(q, n, param; kwargs...) * massratio Πa::Float64 = spin * pifunc(q, n, param; kwargs...) * massratio if regular Ks = bubbledysonreg(Vinvs, Fs, Πs) Ka = bubbledysonreg(Vinva, Fa, Πa) else Ks = bubbledyson(Vinvs, Fs, Πs) Ka = bubbledyson(Vinva, Fa, Πa) end return Ks, Ka end """ function RPA(q, n, param; pifunc = Polarization0_ZeroTemp, Vinv_Bare = coulombinv, regular = false) Dynamic part of RPA interaction. #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. ωn=2πTn - param: other system parameters - pifunc: caller to the polarization function - Vinv_Bare: caller to the bare Coulomb interaction - regular: regularized RPA or not # Return: If set to be regularized, it returns the dynamic part of effective interaction divided by ``v_q - f_q`` ```math \\frac{v_q^{\\pm} Π_0} {1 - v_q^{\\pm} Π_0}. ``` otherwise, return ```math \\frac{(v_q^{\\pm})^2 Π_0} {1 - v_q^{\\pm} Π_0}. ``` """ function RPA(q, n, param; pifunc=Polarization0_ZeroTemp, Vinv_Bare=coulombinv, regular=false, kwargs...) return bubblecorrection(q, n, param; pifunc=pifunc, landaufunc=landauParameter0, Vinv_Bare=Vinv_Bare, regular=regular, kwargs...) end """ function RPAwrapped(Euv, rtol, sgrid::SGT, param; pifunc=Polarization0_ZeroTemp, landaufunc=landauParameterTakada, Vinv_Bare=coulombinv, kwargs...) where {SGT} Return dynamic part and instant part of RPA-interaction Green's function separately. Each part is a MeshArray with inner state (1: spin symmetric part, 2: asymmetric part), and ImFreq and q-grid mesh. #Arguments: - Euv: Euv of DLRGrid - rtol: rtol of DLRGrid - sgrid: momentum grid - param: other system parameters - pifunc: caller to the polarization function - landaufunc: caller to the Landau parameter (exchange-correlation kernel) - Vinv_Bare: caller to the bare Coulomb interaction """ function RPAwrapped(Euv, rtol, sgrid::SGT, param; pifunc=Polarization0_ZeroTemp, landaufunc=landauParameterTakada, Vinv_Bare=coulombinv, kwargs...) where {SGT} # TODO: innerstate should be in the outermost layer of the loop. Hence, the functions such as RPA and Vinv_Bare should be fixed with inner state as argument. @unpack β = param wn_mesh = GreenFunc.ImFreq(β, BOSON; Euv=Euv, rtol=rtol, symmetry=:ph) green_dyn = GreenFunc.MeshArray(1:2, wn_mesh, sgrid; dtype=ComplexF64) green_ins = GreenFunc.MeshArray(1:2, [0,], sgrid; dtype=ComplexF64) for (ki, k) in enumerate(sgrid) for (ni, n) in enumerate(wn_mesh.grid) green_dyn[1, ni, ki], green_dyn[2, ni, ki] = RPA(k, n, param; pifunc=pifunc, Vinv_Bare=Vinv_Bare, regular=true, kwargs...) end green_ins[1, 1, ki], green_ins[2, 1, ki] = Vinv_Bare(k, param) end return green_dyn, green_ins end """ function landauParameterTakada(q, n, param) G factor with Takada's anzats. See Takada(doi:10.1103/PhysRevB.47.5202)(Eq.2.13-2.16). Now Landau parameter F. F(+-)=G(+-)*V #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. ωn=2πTn - param: other system parameters """ function landauParameterTakada(q, n, param; kwargs...) @unpack me, kF, rs, e0s, e0, e0a, β, Λs, Λa, ϵ0 = param if e0 ≈ 0.0 return 0.0, 0.0 end r_s_dl = sqrt(4 * 0.521 * rs / π) C1 = 1 - r_s_dl * r_s_dl / 4.0 * (1 + 0.07671 * r_s_dl * r_s_dl * ((1 + 12.05 * r_s_dl) * (1 + 12.05 * r_s_dl) + 4.0 * 4.254 / 3.0 * r_s_dl * r_s_dl * (1 + 7.0 / 8.0 * 12.05 * r_s_dl) + 1.5 * 1.363 * r_s_dl * r_s_dl * r_s_dl * (1 + 8.0 / 9.0 * 12.05 * r_s_dl)) / (1 + 12.05 * r_s_dl + 4.254 * r_s_dl * r_s_dl + 1.363 * r_s_dl * r_s_dl * r_s_dl) / (1 + 12.05 * r_s_dl + 4.254 * r_s_dl * r_s_dl + 1.363 * r_s_dl * r_s_dl * r_s_dl)) C2 = 1 - r_s_dl * r_s_dl / 4.0 * (1 + r_s_dl * r_s_dl / 8.0 * (log(r_s_dl * r_s_dl / (r_s_dl * r_s_dl + 0.990)) - (1.122 + 1.222 * r_s_dl * r_s_dl) / (1 + 0.533 * r_s_dl * r_s_dl + 0.184 * r_s_dl * r_s_dl * r_s_dl * r_s_dl))) D = inf_sum(r_s_dl, 100) #A1 = (2.0 - C1 - C2) / 4.0 / e0^2 * π A1 = (2.0 - C1 - C2) * (kF * ϵ0 * π^2) / (2 * e0^2 * me) A2 = (C2 - C1) * (kF * ϵ0 * π^2) / (2 * e0^2 * me) B1 = 6 * A1 / (D + 1.0) B2 = 2 * A2 / (1.0 - D) F_s = A1 * e0^2 / ϵ0 / (kF^2 + B1 * q^2) + A2 * e0^2 / ϵ0 / (kF^2 + B2 * q^2) F_a = A1 * e0^2 / ϵ0 / (kF^2 + B1 * q^2) - A2 * e0^2 / ϵ0 / (kF^2 + B2 * q^2) return F_s, F_a end """ function landauParameterMoroni(q, n, param) Analytic expression of G+ factor from diffusion Monte Carlo.(doi:10.1103/PhysRevB.57.14569). Return Landau parameter F+=(G+)*V #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. ωn=2πTn - param: other system parameters """ function landauParameterMoroni(q, n, param; kwargs...) @unpack me, kF, rs, e0s, e0, e0a, β, ϵ0, a0 = param n0 = (kF)^3 / 3 / π^2 if e0 ≈ 0.0 return 0.0, 0.0 end xc = -0.10498 bc = 3.72744 cc = 12.9352 Ac = 0.0621814 function E_corr(rs_dum) result = 0 x = sqrt(rs_dum) X = (x^2 + bc * x + cc) X0 = (xc^2 + bc * xc + cc) Q = sqrt(4 * cc - bc^2) #print("x^2/X=",x^2/X,"\n") #print("x-xc^2/X=",(x-xc)^2/X, "\n") result = Ac * (log(x^2 / X) + 2 * bc / Q * atan(Q / (2 * x + bc)) - bc * xc / X0 * (log((x - xc)^2 / X) + 2 * (bc + 2 * xc) / Q * atan(Q / (2 * x + bc)))) # This expression is in Rydberg unit result = result / (2 * me * a0^2) return result end # step for numerical derivatives step = 0.0000001 x = sqrt(rs) # Calculate parameter A rs1 = (n0 / (n0 + step))^(1.0 / 3.0) * rs rs_1 = (n0 / (n0 - step))^(1.0 / 3.0) * rs deriv_1 = (E_corr(rs1) - E_corr(rs)) / step deriv_2 = (E_corr(rs1) + E_corr(rs_1) - 2 * E_corr(rs)) / step^2 A = 0.25 - kF^2 / 4 / π / e0^2 * (2 * deriv_1 + n0 * deriv_2) #println("A=$(A)") # Calculate parameter B a1 = 2.15 a2 = 0.435 b1 = 1.57 b2 = 0.409 B = (1 + a1 * x + a2 * x^3) / (3 + b1 * x + b2 * x^3) #println("B=$(B)") # Calculate parameter C step = 0.0000001 deriv_1 = (E_corr(rs + step) - E_corr(rs)) / step #deriv_1 = E_corr_p(rs) C = -π / 2 / kF / e0^2 * (E_corr(rs) + rs * deriv_1) #println("C=$(C)") D = B / (A - C) α = 1.5 / rs^0.25 * A / B / D β_0 = 1.2 / B / D Q = q / kF G_s = C * Q^2 + B * Q^2 / (D + Q^2) + α * Q^4 * exp(-β_0 * Q^2) F_s = 4 * π * e0^2 * G_s / q^2 return F_s end @inline function landauParameter0(q, n, param; kwargs...) return 0.0, 0.0 end @inline function landauParameterConst(q, n, param; Fs=0.0, Fa=0.0, massratio=1.0, kwargs...) return Fs / param.NF / massratio, Fa / param.NF / massratio end @inline function counterterm(q, n, param; landaufunc, kwargs...) fs, fa = landaufunc(q, n, param; kwargs...) return fs, fa end @inline function countertermConst(q, n, param; landaufunc, Cs=0.0, Ca=0.0, massratio=1.0, kwargs...) return Cs / param.NF / massratio, Ca / param.NF / massratio end """ function KO(q, n, param; pifunc = Polarization0_ZeroTemp, landaufunc = landauParameterTakada, Vinv_Bare = coulombinv, regular = false, kwargs...) Dynamic part of KO interaction. Returns the spin symmetric part and asymmetric part separately. #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. ωn=2πTn - param: other system parameters - pifunc: caller to the polarization function - landaufunc: caller to the Landau parameter (exchange-correlation kernel) - Vinv_Bare: caller to the bare Coulomb interaction - regular: regularized RPA or not # Return: If set to be regularized, it returns the dynamic part of effective interaction divided by ``v_q - f_q`` ```math \\frac{(v_q^{\\pm} - f_q^{\\pm}) Π_0} {1 - (v_q^{\\pm} - f_q^{\\pm}) Π_0}. ``` otherwise, return ```math \\frac{(v_q^{\\pm} - f_q^{\\pm})^2 Π_0} {1 - (v_q^{\\pm} - f_q^{\\pm}) Π_0}. ``` """ function KO(q, n, param; pifunc=Polarization0_ZeroTemp, landaufunc=landauParameterTakada, Vinv_Bare=coulombinv, regular=false, kwargs...) return bubblecorrection(q, n, param; pifunc=pifunc, landaufunc=landaufunc, Vinv_Bare=Vinv_Bare, regular=regular, kwargs...) end """ function KOwrapped(Euv, rtol, sgrid::SGT, param; int_type=:ko, pifunc=Polarization0_ZeroTemp, landaufunc=landauParameterTakada, Vinv_Bare=coulombinv, kwargs...) where {SGT} Return dynamic part and instant part of KO-interaction Green's function separately. Each part is a MeshArray with inner state (1: spin symmetric part, 2: asymmetric part), and ImFreq and q-grid mesh. #Arguments: - Euv: Euv of DLRGrid - rtol: rtol of DLRGrid - sgrid: momentum grid - param: other system parameters - pifunc: caller to the polarization function - landaufunc: caller to the Landau parameter (exchange-correlation kernel) - Vinv_Bare: caller to the bare Coulomb interaction """ function KOwrapped(Euv, rtol, sgrid::SGT, param; int_type=:ko, pifunc=Polarization0_ZeroTemp, landaufunc=landauParameterTakada, Vinv_Bare=coulombinv, kwargs...) where {SGT} # TODO: innerstate should be in the outermost layer of the loop. Hence, the functions such as KO and Vinv_Bare should be fixed with inner state as argument. @unpack β = param wn_mesh = GreenFunc.ImFreq(β, BOSON; Euv=Euv, rtol=rtol, symmetry=:ph) green_dyn = GreenFunc.MeshArray(1:2, wn_mesh, sgrid; dtype=ComplexF64) green_ins = GreenFunc.MeshArray(1:2, [0,], sgrid; dtype=ComplexF64) for (ki, k) in enumerate(sgrid) for (ni, n) in enumerate(wn_mesh.grid) green_dyn[1, ni, ki], green_dyn[2, ni, ki] = KO(k, n, param; pifunc=pifunc, landaufunc=landaufunc, Vinv_Bare=Vinv_Bare, kwargs...) end green_ins[1, 1, ki], green_ins[2, 1, ki] = Vinv_Bare(k, param) end return green_dyn, green_ins end """ function KO_total(q, n, param; pifunc = Polarization0_ZeroTemp, landaufunc = landauParameterTakada, Vinv_Bare = coulombinv, counter_term = counterterm, kwargs...) Dynamic part of KO interaction. Returns the spin symmetric part and asymmetric part separately. #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. ωn=2πTn - param: other system parameters - pifunc: caller to the polarization function - landaufunc: caller to the Landau parameter (exchange-correlation kernel) - Vinv_Bare: caller to the bare Coulomb interaction - counter_term: counterterm, by default, it is the landaufunc # Return: Return the total effective interaction ```math W^{\\pm} = \\frac{(v_q^{\\pm} - f_q^{\\pm}) Π_0} {1 - (v_q^{\\pm} - f_q^{\\pm}) Π_0} + C_q^{\\pm}. ``` which reduces to the convential KO interaction if ``C_q^{\\pm} \\equiv f_q^{\\pm}`` """ function KO_total(q, n, param; pifunc=Polarization0_ZeroTemp, landaufunc=landauParameterTakada, Vinv_Bare=coulombinv, counter_term=counterterm, kwargs...) @unpack spin = param if abs(q) < EPS q = EPS end Π::Float64 = spin * pifunc(q, n, param; kwargs...) fs, fa = landaufunc(q, n, param; kwargs...) Cs, Ca = counter_term(q, n, param; landaufunc=landaufunc, kwargs...) Vinvs, Vinva = Vinv_Bare(q, param) if param.gs ≈ 0.0 Ka = (-fs) / (1 - (-fs) * Π) + Cs else Ks = 1.0 / (Vinvs / (1 - fs * Vinvs) - Π) + Cs end if param.ga ≈ 0.0 Ka = (-fa) / (1 - (-fa) * Π) + Ca else Ka = 1.0 / (Vinva / (1 - fa * Vinva) - Π) + Ca end return Ks, Ka end function RPA_total(q, n, param; pifunc=Polarization0_ZeroTemp, Vinv_Bare=coulombinv, kwargs...) @unpack spin = param if abs(q) < EPS q = EPS end Π::Float64 = spin * pifunc(q, n, param) Vinvs, Vinva = Vinv_Bare(q, param) Ws = 1.0 / (Vinvs - (Π)) Wa = 1.0 / (Vinva - (Π)) return Ws, Wa end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
15480
""" Provide Legendre decomposed interaction that could be useful for calculating self-energy and solving gap-function equation of superconductivity problems. """ module LegendreInteraction # using Parameters, GreenFunc, Lehmann, LegendrePolynomials, CompositeGrids # include(srcdir*"/parameter.jl") # using .Parameter # include(srcdir*"/convention.jl") # using .Convention # include(srcdir*"/polarization.jl") # using .Polarization # include(srcdir*"/interaction.jl") # using .Interaction using Base.Threads using ..Parameter, ..Convention, ..Polarization, ..Interaction using ..Parameters, ..GreenFunc, ..Lehmann, ..LegendrePolynomials, ..CompositeGrids export DCKernel @inline function spin_factor(spin_state) if spin_state == :singlet factor = 1.0 elseif spin_state == :triplet factor = -3.0 elseif spin_state == :sigma factor = 3.0 else throw(UndefVarError(spin_state)) end return factor end function interaction_dynamic(q, n, param, int_type, spin_state; kwargs...) # a wrapper for dynamic part of effective interaction # for rpa simply return rpa # for ko return ks+ka for singlet, ks-3ka for triplet @unpack dim = param if dim != 2 && dim != 3 throw(UndefVarError(dim)) end if int_type == :rpa if dim == 3 # ks, ka = RPA(q, n, param) ks, ka = RPA(q, n, param; regular=true, kwargs...) .* Interaction.coulomb(q, param) elseif dim == 2 # ks, ka = RPA(q, n, param; Vinv_Bare=Interaction.coulombinv_2d) ks, ka = RPA(q, n, param; Vinv_Bare=Interaction.coulombinv_2d, regular=true, kwargs...) .* Interaction.coulomb_2d(q, param) end elseif int_type == :ko if dim == 3 # ks, ka = KO(q, n, param) ks, ka = KO(q, n, param; regular=true, kwargs...) .* (Interaction.coulomb(q, param) .- Interaction.landauParameterTakada(q, n, param)) elseif dim == 2 ks, ka = KO(q, n, param; Vinv_Bare=Interaction.coulombinv_2d, kwargs...) end elseif int_type == :ko_const if dim == 3 # ks, ka = KO(q, n, param) ks, ka = KO(q, n, param; regular=true, landaufunc=Interaction.landauParameterConst, kwargs...) .* (Interaction.coulomb(q, param) .- Interaction.landauParameterConst(q, n, param)) elseif dim == 2 error("not implemented!") end else throw(UndefVarError(int_type)) end return ks + spin_factor(spin_state) * ka end @inline function interaction_instant(q, param, spin_state; kwargs...) @unpack dim = param if dim != 2 && dim != 3 throw(UndefVarError(dim)) end if dim == 3 Vs, Va = coulomb(q, param) elseif dim == 2 Vs, Va = coulomb_2d(q, param) end return (Vs + spin_factor(spin_state) * Va) end @inline function kernel_integrand(k, p, q, n, channel, param, int_type, spin_state; kwargs...) legendre_x = (k^2 + p^2 - q^2) / 2 / k / p if (abs(abs(legendre_x) - 1) < 1e-12) legendre_x = sign(legendre_x) * 1 end # convention changed, now interaction_dynamic already included the V_Bare return q * Pl(legendre_x, channel) * interaction_dynamic(q, n, param, int_type, spin_state; kwargs...) end @inline function kernel0_integrand(k, p, q, channel, param, spin_state; kwargs...) legendre_x = (k^2 + p^2 - q^2) / 2 / k / p if (abs(abs(legendre_x) - 1) < 1e-12) legendre_x = sign(legendre_x) * 1 end @assert -1 <= legendre_x <= 1 "k=$k,p=$p,q=$q" return q * Pl(legendre_x, channel) * interaction_instant(q, param, spin_state; kwargs...) end @inline function kernel_integrand2d(k, p, θ, n, channel, param, int_type, spin_state; kwargs...) x = cos(θ) q2 = (k - p)^2 + 2k * p * (1 - x) if x == 1 || q2 <= 0 q2 = (k - p)^2 + k * p * θ^2 end return cos(channel * θ) * interaction_dynamic(√q2, n, param, int_type, spin_state; kwargs...) end @inline function kernel0_integrand2d(k, p, θ, channel, param, spin_state; kwargs...) x = cos(θ) q2 = (k - p)^2 + 2k * p * (1 - x) if x == 1 || q2 <= 0 q2 = (k - p)^2 + k * p * θ^2 # println("$k, $p, $q2, $((k - p)^2), $x, $θ") end return cos(channel * θ) * interaction_instant(√q2, param, spin_state; kwargs...) end function helper_function(y::Float64, n::Int, W, param; Nk::Int=40, minK::Float64=1e-12 * param.kF, order::Int=6) # return the helper function @unpack kF, β = param # generate a new grid for every calculation kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, y], [0.0, min(y, 2kF)], Nk, minK, order) integrand = zeros(Float64, kgrid.size) for (ki, k) in enumerate(kgrid) integrand[ki] = k^n * W(k) end H = Interp.integrate1D(integrand, kgrid) return H end function helper_function_grid(ygrid, intgrid, n::Int, W, param) # return the helper function @unpack kF, β, e0, ϵ0 = param # generate a new grid for every calculation #kgrid = CompositeGrid.LogDensedGrid(:uniform, [0.0, grid[end]], [0.0,min(grid[end],2kF)], Nk, minK, order) kgrid = intgrid grid = ygrid helper = zeros(Float64, length(grid)) integrand = zeros(Float64, kgrid.size) for (ki, k) in enumerate(kgrid) # integrand[ki] = k^(n-2) * W(k) * e0^2 / ϵ0 integrand[ki] = k^(n) * W(k) end for i in 1:length(grid) if i == 1 x1, x2, hprev = 0.0, grid[1], 0.0 else x1, x2, hprev = grid[i-1], grid[i], helper[i-1] end helper[i] = Interp.integrate1D(integrand, kgrid, [x1, x2]) + hprev # helper[i] = Interp.integrate1D(integrand, kgrid, [EPS,grid[i]]) # @assert isfinite(helper[i]) "fail at $(grid[i])" end return helper end struct DCKernel{C} int_type::Symbol spin_state::Symbol channel::Int param::Parameter.Para kgrid::C qgrids::Vector{CompositeGrid.Composite} dlrGrid::DLRGrid kernel_bare::Array{Float64,2} kernel::Array{Float64,3} function DCKernel(int_type, spin_state, channel, param, kgrid::C, qgrids, dlrGrid, kernel_bare, kernel) where {C} return new{C}(int_type, spin_state, channel, param, kgrid, qgrids, dlrGrid, kernel_bare, kernel) end end function DCKernel_2d(param, Euv, rtol, Nk, maxK, minK, order, int_type, channel, spin_state=:auto; kgrid=CompositeGrid.LogDensedGrid(:cheb, [0.0, maxK], [0.0, param.kF], Nk, minK, order), kwargs...) @unpack kF, β = param if spin_state == :sigma # for self-energy, always use ℓ=0 channel = 0 elseif spin_state == :auto # automatically assign spin_state, triplet for even, singlet for odd channel spin_state = (channel % 2 == 0) ? (:triplet) : (:singlet) end bdlr = DLRGrid(Euv, β, rtol, false, :ph) qgrids = [CompositeGrid.LogDensedGrid(:gauss, [0.0, maxK], [k, kF], Nk, minK, order) for k in kgrid.grid] qgridmax = maximum([qg.size for qg in qgrids]) # θgrid = SimpleGrid.GaussLegendre{Float64}([0, 2π], 100) # θgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, π], [0.0, π], Nk, 1e-7, order) θgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, π], [0.0, π], Nk, 1e-7 * kF, order) # println(θgrid.size) # println(θgrid.grid) kernel_bare = zeros(Float64, (length(kgrid.grid), (qgridmax))) kernel = zeros(Float64, (length(kgrid.grid), (qgridmax), length(bdlr.n))) data0 = zeros(Float64, length(θgrid.grid)) # data = zeros(Float64, (length(θgrid.grid), length(bdlr.n))) for (ki, k) in enumerate(kgrid.grid) for (pi, p) in enumerate(qgrids[ki].grid) for (θi, θ) in enumerate(θgrid.grid) data0[θi] = kernel0_integrand2d(k, p, θ, channel, param, spin_state; kwargs...) end kernel_bare[ki, pi] = Interp.integrate1D(data0, θgrid) * 2 # println("$ki,$pi, $(kernel_bare[ki,pi])") @assert isfinite(kernel_bare[ki, pi]) "fail kernel_bare at $ki,$pi, ($k, $p) with $(kernel_bare[ki,pi]) \n $data" # @threads for (ni, n) in collect(enumerate(bdlr.n)) for (ni, n) in enumerate(bdlr.n) for (θi, θ) in enumerate(θgrid.grid) # data[θi, ni] = kernel_integrand2d(k, p, θ, n, channel, param, int_type, spin_state) data0[θi] = kernel_integrand2d(k, p, θ, n, channel, param, int_type, spin_state; kwargs...) end # data[:, ni] = [kernel_integrand2d(k, p, θ, n, channel, param, int_type, spin_state) for θ in θgrid.grid] kernel[ki, pi, ni] = Interp.integrate1D(data0, θgrid) * 2 # kernel[ki, pi, ni] = Interp.integrate1D(data[:, ni], θgrid) * 2 # ni == 1 && println("$ki,$pi, $n $(kernel[ki, pi, ni])") @assert isfinite(kernel[ki, pi, ni]) "fail kernel at $ki,$pi,$ni, with $(kernel[ki,pi,ni])" end end end return DCKernel(int_type, spin_state, channel, param, kgrid, qgrids, bdlr, kernel_bare, kernel) end function DCKernel_2d(param; Euv=param.EF * 100, rtol=1e-10, Nk=8, maxK=param.kF * 10, minK=param.kF * 1e-7, order=4, int_type=:rpa, channel=0, spin_state=:auto, kwargs...) return DCKernel_2d(param, Euv, rtol, Nk, maxK, minK, order, int_type, channel, spin_state; kwargs...) end function DCKernel_old(param, Euv, rtol, Nk, maxK, minK, order, int_type, channel, spin_state=:auto; kgrid=CompositeGrid.LogDensedGrid(:cheb, [0.0, maxK], [0.0, param.kF], Nk, minK, order), kwargs...) @unpack kF, β = param if spin_state == :sigma # for self-energy, always use ℓ=0 channel = 0 elseif spin_state == :auto # automatically assign spin_state, triplet for even, singlet for odd channel spin_state = (channel % 2 == 0) ? (:triplet) : (:singlet) end bdlr = DLRGrid(Euv, β, rtol, false, :ph) qgrids = [CompositeGrid.LogDensedGrid(:gauss, [0.0, maxK], [k, kF], Nk, minK, order) for k in kgrid.grid] qgridmax = maximum([qg.size for qg in qgrids]) #println(qgridmax) kernel_bare = zeros(Float64, (length(kgrid.grid), (qgridmax))) kernel = zeros(Float64, (length(kgrid.grid), (qgridmax), length(bdlr.n))) int_grid_base = CompositeGrid.LogDensedGrid(:uniform, [0.0, 2.1 * maxK], [0.0, 2kF], 2Nk, 0.01minK, 2) for (ki, k) in enumerate(kgrid.grid) for (pi, p) in enumerate(qgrids[ki].grid) if abs(k - p) > EPS kmp = abs(k - p) < EPS ? EPS : abs(k - p) kpp = k + p im, ip = floor(int_grid_base, kmp), floor(int_grid_base, kpp) int_panel = Float64[] push!(int_panel, kmp) if im < ip for i in im+1:ip push!(int_panel, int_grid_base[i]) end end push!(int_panel, kpp) int_panel = SimpleGrid.Arbitrary{Float64}(int_panel) SubGridType = SimpleGrid.GaussLegendre{Float64} subgrids = subgrids = Vector{SubGridType}([]) for i in 1:int_panel.size-1 _bound = [int_panel[i], int_panel[i+1]] push!(subgrids, SubGridType(_bound, order)) end int_grid = CompositeGrid.Composite{Float64,typeof(int_panel),SubGridType}(int_panel, subgrids) data = [kernel0_integrand(k, p, q, channel, param, spin_state; kwargs...) for q in int_grid.grid] kernel_bare[ki, pi] = Interp.integrate1D(data, int_grid) for (ni, n) in enumerate(bdlr.n) data = [kernel_integrand(k, p, q, n, channel, param, int_type, spin_state; kwargs...) for q in int_grid.grid] kernel[ki, pi, ni] = Interp.integrate1D(data, int_grid) @assert isfinite(kernel[ki, pi, ni]) "fail kernel at $ki,$pi,$ni, with $(kernel[ki,pi,ni])" end else kernel_bare[ki, pi] = 0 for (ni, n) in enumerate(bdlr.n) kernel[ki, pi, ni] = 0 end end end end return DCKernel(int_type, spin_state, channel, param, kgrid, qgrids, bdlr, kernel_bare, kernel) end function DCKernel_old(param; Euv=param.EF * 100, rtol=1e-10, Nk=8, maxK=param.kF * 10, minK=param.kF * 1e-7, order=4, int_type=:rpa, channel=0, spin_state=:auto) return DCKernel_old(param, Euv, rtol, Nk, maxK, minK, order, int_type, channel, spin_state) end function DCKernel0(param; Euv=param.EF * 100, rtol=1e-10, Nk=8, maxK=param.kF * 10, minK=param.kF * 1e-7, order=4, int_type=:rpa, spin_state=:auto, kwargs...) return DCKernel0(param, Euv, rtol, Nk, maxK, minK, order, int_type, spin_state; kwargs...) end function DCKernel0(param, Euv, rtol, Nk, maxK, minK, order, int_type, spin_state=:auto; kgrid=CompositeGrid.LogDensedGrid(:cheb, [0.0, maxK], [0.0, param.kF], Nk, minK, order), kwargs...) # use helper function @unpack kF, β = param channel = 0 if spin_state == :sigma # for self-energy, always use ℓ=0 channel = 0 elseif spin_state == :auto # automatically assign spin_state, triplet for even, singlet for odd channel spin_state = (channel % 2 == 0) ? (:triplet) : (:singlet) end bdlr = DLRGrid(Euv, β, rtol, false, :ph) qgrids = [CompositeGrid.LogDensedGrid(:gauss, [0.0, maxK], [k, kF], Nk, minK, order) for k in kgrid.grid] qgridmax = maximum([qg.size for qg in qgrids]) #println(qgridmax) kernel_bare = zeros(Float64, (length(kgrid.grid), (qgridmax))) kernel = zeros(Float64, (length(kgrid.grid), (qgridmax), length(bdlr.n))) helper_grid = CompositeGrid.LogDensedGrid(:cheb, [0.0, 2.1 * maxK], [0.0, 2kF], 2Nk, 0.01minK, 2order) intgrid = CompositeGrid.LogDensedGrid(:cheb, [0.0, helper_grid[end]], [0.0, 2kF], 2Nk, 0.01minK, 2order) # dynamic for (ni, n) in enumerate(bdlr.n) # helper = zeros(Float64, helper_grid.size) # for (yi, y) in enumerate(helper_grid) # helper[yi] = helper_function(y, 1, u->interaction_dynamic(u,n,param,int_type,spin_state),param) # end helper = helper_function_grid(helper_grid, intgrid, 1, u -> interaction_dynamic(u, n, param, int_type, spin_state; kwargs...), param) for (ki, k) in enumerate(kgrid.grid) for (pi, p) in enumerate(qgrids[ki].grid) Hp, Hm = Interp.interp1D(helper, helper_grid, k + p), Interp.interp1D(helper, helper_grid, abs(k - p)) kernel[ki, pi, ni] = (Hp - Hm) end end end # instant # helper = zeros(Float64, helper_grid.size) # for (yi, y) in enumerate(helper_grid) # helper[yi] = helper_function(y, 1, u->interaction_instant(u,param,spin_state),param) # end helper = helper_function_grid(helper_grid, intgrid, 1, u -> interaction_instant(u, param, spin_state; kwargs...), param) # helper = helper_function_grid(helper_grid, intgrid, 1, u -> 1.0, param) for (ki, k) in enumerate(kgrid.grid) for (pi, p) in enumerate(qgrids[ki].grid) Hp, Hm = Interp.interp1D(helper, helper_grid, k + p), Interp.interp1D(helper, helper_grid, abs(k - p)) kernel_bare[ki, pi] = (Hp - Hm) end end return DCKernel(int_type, spin_state, channel, param, kgrid, qgrids, bdlr, kernel_bare, kernel) end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
6943
""" Template of parameter. A submodule of ElectronGas. Use the convention where ħ=1, k_B=1. Only stores parameters that might change for purposes. """ module Parameter # using Parameters using ..Parameters # using Roots, SpecialFunctions # using Polylogarithms @with_kw struct Para WID::Int = 1 dim::Int = 3 # dimension (D=2 or 3, doesn't work for other D!!!) spin::Int = 2 # number of spins # prime parameters ϵ0::Float64 = 1 / (4π) e0::Float64 = sqrt(2) # electron charge me::Float64 = 0.5 # electron mass EF::Float64 = 1.0 #kF^2 / (2me) β::Float64 = 200 # bare inverse temperature μ::Float64 = 1.0 # artificial parameters Λs::Float64 = 0.0 # Yukawa-type spin-symmetric interaction ~1/(q^2+Λs) Λa::Float64 = 0.0 # Yukawa-type spin-antisymmetric interaction ~1/(q^2+Λa) gs::Float64 = 1.0 # spin-symmetric coupling ga::Float64 = 0.0 # spin-antisymmetric coupling # derived parameters beta::Float64 = β * EF Θ::Float64 = 1.0 / β / EF T::Float64 = 1.0 / β n::Float64 = (dim == 3) ? (EF * 2 * me)^(3 / 2) / (6π^2) * spin : me * EF / π Rs::Float64 = (dim == 3) ? (3 / (4π * n))^(1 / 3) : sqrt(1 / (π * n)) a0::Float64 = 4π * ϵ0 / (me * e0^2) rs::Float64 = Rs / a0 kF::Float64 = sqrt(2 * me * EF) espin::Float64 = e0 e0s::Float64 = e0 e0a::Float64 = espin NF::Float64 = (dim == 3) ? spin * me * kF / 2 / π^2 : spin * me / 2 / π ωp::Float64 = (dim == 3) ? sqrt(4π * e0^2 * n / me) : 0.0 # plasma frequency qTF::Float64 = (dim == 3) ? sqrt(4π * e0^2 * NF) : 0.0 # inverse thomas-fermi screening length # for spin-2 and 3d case, ω_p=v_F*q_TF/sqrt(3) end derived_para_names = (:beta, :Θ, :T, :n, :Rs, :a0, :rs, :kF, :espin, :e0s, :e0a, :NF, :ωp, :qTF) """ function derive(param::Para; kws...) Reconstruct a new Para with given key word arguments. This is needed because the default reconstruct generated by Parameters.jl could not handle derived parameters correctly. #Arguments: - param: only "non-derived" fields that's not mentioned in kws are extracted from param - kws...: new values """ derive(param::Para; kws...) = _reconstruct(param, kws) derive(param::Para, di::Union{AbstractDict,Tuple{Symbol,Any}}) = _reconstruct(param, di) # reconstruct(pp::Para, di) = reconstruct(Para, pp, di) # reconstruct(pp; kws...) = reconstruct(pp, kws) # reconstruct(Para::Type, pp; kws...) = reconstruct(Para, pp, kws) function _reconstruct(pp::Para, di) # default reconstruct can't handle derived parameters correctly di = !isa(di, AbstractDict) ? Dict(di) : copy(di) ns = fieldnames(Para) args = [] for (i, n) in enumerate(ns) if n ∉ derived_para_names # if exist in di, use value from di # the default value is from pp push!(args, (n, pop!(di, n, getfield(pp, n)))) else pop!(di, n, getfield(pp, n)) end end length(di) != 0 && error("Fields $(keys(di)) not in type $T") dargs = Dict(args) return Para(; dargs...) end # function Base.getproperty(obj::Para, sym::Symbol) # if sym === :beta # dimensionless beta # return obj.β * obj.EF # elseif sym === :Θ # dimensionless temperature # return 1.0 / obj.β / obj.EF # elseif sym === :T # return 1.0 / obj.β # elseif sym === :n # return (obj.dim == 3) ? (obj.EF * 2 * obj.me)^(3 / 2) / (6π^2) * obj.spin : obj.me * obj.EF / π # elseif sym === :Rs # return (obj.dim == 3) ? (3 / (4π * obj.n))^(1 / 3) : sqrt(1 / (π * obj.n)) # elseif sym === :a0 # return 4π * obj.ϵ0 / (obj.me * obj.e0^2) # elseif sym === :rs # return obj.Rs / obj.a0 # elseif sym === :kF # return sqrt(2 * obj.me * obj.EF) # elseif sym === :e0s # return obj.e0 # elseif sym === :e0a # return obj.espin # else # fallback to getfield # return getfield(obj, sym) # end # end # """ # function chemical_potential(beta) # generate chemical potential μ with given beta and density conservation. # #Arguments: # - beta: dimensionless inverse temperature # """ # function chemical_potential(beta, dim) # f(β, μ) = real(polylog(dim / 2, -exp(β * μ))) + 1 / gamma(1 + dim / 2) * (β)^(dim / 2) # g(μ) = f(beta, μ) # return find_zero(g, (-1e4, 1)) # end """ function fullUnit(ϵ0, e0, me, EF, β) generate Para with a complete set of parameters, no value presumed. #Arguments: - ϵ0: vacuum permittivity - e0: electron charge - me: electron mass - EF: Fermi energy - β: inverse temperature """ @inline function fullUnit(ϵ0, e0, me, EF, β, dim=3, spin=2; kwargs...) # μ = try # chemical_potential(β * EF, dim) * EF # catch e # # if isa(e, StackOverflowError) # EF # end μ = EF # println(kwargs) para = Para(dim=dim, spin=spin, ϵ0=ϵ0, e0=e0, me=me, EF=EF, β=β, μ=μ ) # return para return derive(para, kwargs) end """ function defaultUnit(Θ, rs) assume 4πϵ0=1, me=0.5, EF=1 #Arguments: - Θ: dimensionless temperature. Since EF=1 we have β=beta - rs: Wigner-Seitz radius over Bohr radius. """ @inline function defaultUnit(Θ, rs, dim=3, spin=2; kwargs...) ϵ0 = 1 / (4π) e0 = (dim == 3) ? sqrt(2 * rs / (9π / (2spin))^(1 / 3)) : sqrt(sqrt(2) * rs) me = 0.5 EF = 1 β = 1 / Θ / EF return fullUnit(ϵ0, e0, me, EF, β, dim, spin; kwargs...) end """ function rydbergUnit(Θ, rs, dim = 3, spin = 2; kwargs...) assume 4πϵ0=1, me=0.5, e0=sqrt(2) #Arguments: - Θ: dimensionless temperature. beta could be different from β - rs: Wigner-Seitz radius over Bohr radius. - dim: dimension of the system - spin: spin = 1 or 2 - kwargs: user may explicity set other paramters using the key/value pairs """ @inline function rydbergUnit(Θ, rs, dim=3, spin=2; kwargs...) ϵ0 = 1 / (4π) e0 = sqrt(2) me = 0.5 kF = (dim == 3) ? (9π / (2spin))^(1 / 3) / rs : sqrt(4 / spin) / rs EF = kF^2 / (2me) β = 1 / Θ / EF return fullUnit(ϵ0, e0, me, EF, β, dim, spin; kwargs...) end """ function atomicUnit(Θ, rs, dim = 3, spin = 2; kwargs...) assume 4πϵ0=1, me=1, e0=1 #Arguments: - Θ: dimensionless temperature. beta could be different from β - rs: Wigner-Seitz radius over Bohr radius. - dim: dimension of the system - spin: spin = 1 or 2 - kwargs: user may explicity set other paramters using the key/value pairs """ @inline function atomicUnit(Θ, rs, dim=3, spin=2; kwargs...) ϵ0 = 1 / (4π) e0 = 1 me = 1 kF = (dim == 3) ? (9π / (2spin))^(1 / 3) / rs : sqrt(4 / spin) / rs EF = kF^2 / (2me) β = 1 / Θ / EF return fullUnit(ϵ0, e0, me, EF, β, dim, spin; kwargs...) end """ isZeroT(para) = (para.β == Inf) check if it is at zero temperature or not. """ isZeroT(para) = (para.β == Inf) export Para, Param end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
24870
module Polarization using ..GreenFunc, ..CompositeGrids using ..Parameter using ..Parameters using ..Convention export Polarization0_ZeroTemp, Polarization0_FiniteTemp # Analytical calculated integrand of Π0 in 2D. @inline function _ΠT2d_integrand(k, q, ω, param) @unpack me, β, μ = param density = me / 2π nk = 1.0 / (exp(β * (k^2 / 2 / me - μ)) + 1) error("not implemeted!") return nothing end # Analytical calculated integrand of Π0 in 3D. @inline function _ΠT3d_integrand(k, q, ω, param) @unpack me, β, μ = param # ω only appears as ω^2 so no need to check sign of ω nk = 1.0 / (exp(β * (k^2 / 2 / me - μ)) + 1) # if q is too small, use safe form if q < 1e-16 && ω ≈ 0 if abs(q - 2 * k)^2 < 1e-16 return 0.0 else return -k * me / (4 * π^2) * nk * ((8 * k) / ((q - 2 * k)^2)) end elseif q < 1e-16 && !(ω ≈ 0) return -k * me / (4 * π^2) * nk * ((8 * k * q^2) / (4 * me^2 * ω^2 + (q^2 - 2 * k * q)^2)) else return -k * me / (4 * π^2 * q) * nk * log1p((8 * k * q^3) / (4 * me^2 * ω^2 + (q^2 - 2 * k * q)^2)) end # if ω==0 && abs(q*(k*2-q)*β)<1e-16 # return 0.0 # elseif ω!=0 && k^2*q^2/4/me^2<ω^2*1e-16 # 2*q^2*k^2/(π^2*ω^2)/(exp(β*(k^2/2/me-μ))+1)/(8*me) # else # return k*me/(2*π^2*q)/(exp(β*(k^2/2/me-μ))+1)*log((4*me^2*ω^2+(q^2+2*k*q)^2)/(4*me^2*ω^2+(q^2-2*k*q)^2)) # return k*me/(2*π^2*q)/(exp(β*(k^2/2/me-μ))+1)*log1p((8*k*q^3)/(4*me^2*ω^2+(q^2-2*k*q)^2)) # end end # Analytical calculated integrand of the ladder in 3D. @inline function _LadderT3d_integrand(x, q, ω, param) @unpack me, β, μ = param # ω only appears as ω^2 so no need to check sign of ω k = x / (1 - x) nk = 1.0 / (exp(β * (k^2 / 2 / me - μ)) + 1) if q > 1e-6 * param.kF a = ω * 1im - k^2 / me - q^2 / 2 / me + 2μ b = q * k / me return me / (2π)^2 * (k / q * (log(a + b) - log(a - b)) * (2 * nk - 1) - 2) / (1 - x)^2 # additional factor 1/(1-x)^2 is from the Jacobian else return me / (2π)^2 * (2k^2 / me / (ω * 1im - k^2 / me + 2μ) * (2 * nk - 1) - 2) / (1 - x)^2 # additional factor 1/(1-x)^2 is from the Jacobian end # if q is too small, use safe form # if q < 1e-16 && ω ≈ 0 # if abs(q - 2 * k)^2 < 1e-16 # return 0.0 # else # return -k * me / (4 * π^2) * nk * ((8 * k) / ((q - 2 * k)^2)) # end # elseif q < 1e-16 && !(ω ≈ 0) # return -k * me / (4 * π^2) * nk * ((8 * k * q^2) / (4 * me^2 * ω^2 + (q^2 - 2 * k * q)^2)) # else # return -k * me / (4 * π^2 * q) * nk * log1p((8 * k * q^3) / (4 * me^2 * ω^2 + (q^2 - 2 * k * q)^2)) # end end function finitetemp_kgrid(q::Float64, kF::Float64, maxk=20, scaleN=20, minterval=1e-6, gaussN=10) mink = (q < 1e-16 / minterval) ? minterval * kF : minterval * min(q, kF) # dense point near k_F and q/2 kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, maxk * kF], [0.5 * q, kF], scaleN, mink, gaussN) return kgrid end function finitetemp_kgrid_ladder(μ::Float64, m::Float64, q::Float64, kF::Float64, scaleN=20, minterval=1e-6, gaussN=10) # the grid k=(0, \infty) of the momentum is maked to x=k/(1+k) where x is in (0,1) # the reverse map is k=x/(1-x) # See the box in the link https://numericaleft.github.io/MCIntegration.jl/dev/ titled as "Integrate over different domains" mink = (q < 1e-16 / minterval) ? minterval * kF : minterval * min(q, kF) mixX = mink / (1 + mink) if q >= sqrt(8 * μ * m) x = kF / (1 + kF) kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, 1.0], [0.0, x], scaleN, mink, gaussN) else k1 = abs(q - sqrt(8 * μ * m - q^2)) / 2 k2 = (q + sqrt(8 * μ * m - q^2)) / 2 x1 = k1 / (1 + k1) x2 = k2 / (1 + k2) x3 = kF / (1 + kF) kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, 1.0], sort([x1, x2, x3]), scaleN, mink, gaussN) end return kgrid end """ function Ladder0_FiniteTemp(q::Float64, n::Int, param, scaleN=20, minterval=1e-6, gaussN=10) Finite temperature ladder function for matsubara frequency and momentum. Analytically sum over total incoming frequency and angular dependence of momentum, and numerically calculate integration of magnitude of momentum. Assume G_0^{-1} = iω_n - (k^2/(2m) - mu) The ladder function is defined as ```math \\int \\frac{d^3 \\vec{p}}{\\left(2π^3\\right)} T \\sum_{i ω_n} \\frac{1}{iω_n+iΩ_n-\\frac{(\\vec{k}+\\vec{p})^2}{2 m}+μ} \\frac{1}{-iω_n-\\frac{p^2}{2 m}+μ} - \\frac{m}{2π^2}Λ ``` where we subtract the UV divergent term that is a constant proportional to the UV cutoff Λ. #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. Ωn=2πTn - param: other system parameters - scaleN: optional, N of Log grid in LogDensedGrid, check CompositeGrids for more detail - minterval: optional, actual minterval of grid is this value times min(q,kF) - gaussN: optional, N of GaussLegendre grid in LogDensedGrid. """ function Ladder0_FiniteTemp(q::Float64, n::Int, param; scaleN=20, minterval=1e-6, gaussN=10) @unpack dim, kF, β, me, μ = param if dim != 3 error("No support for finite-temperature polarization in $dim dimension!") end # check sign of q, use -q if negative if q < 0 q = -q end # mink = (q < 1e-16 / minterval) ? minterval * kF : minterval * min(q, kF) # kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, maxk * kF], [0.5 * q, kF], scaleN, mink, gaussN) kgrid = finitetemp_kgrid_ladder(μ, me, q, kF, scaleN, minterval, gaussN) integrand = zeros(ComplexF64, kgrid.size) if dim == 3 for (ki, k) in enumerate(kgrid.grid) integrand[ki] = _LadderT3d_integrand(k, q, 2π * n / β, param) @assert !isnan(integrand[ki]) "nan at k=$k, q=$q" end end return Interp.integrate1D(integrand, kgrid) end """ function Polarization0_FiniteTemp(q::Float64, n::Int, param, maxk=20, scaleN=20, minterval=1e-6, gaussN=10) Finite temperature one-spin Π0 function for matsubara frequency and momentum. Analytically sum over transfer frequency and angular dependence of momentum, and numerically calculate integration of magnitude of momentum. Slower(~200μs) than Polarization0_ZeroTemp. Assume G_0^{-1} = iω_n - (k^2/(2m) - mu) #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. ωn=2πTn - param: other system parameters - maxk: optional, upper limit of integral -> maxk*kF - scaleN: optional, N of Log grid in LogDensedGrid, check CompositeGrids for more detail - minterval: optional, actual minterval of grid is this value times min(q,kF) - gaussN: optional, N of GaussLegendre grid in LogDensedGrid. """ function Polarization0_FiniteTemp(q::Float64, n::Int, param; maxk=20, scaleN=20, minterval=1e-6, gaussN=10) @unpack dim, kF, β = param if dim != 2 && dim != 3 error("No support for finite-temperature polarization in $dim dimension!") end ####################### ! temprary fix ####################################### # !TODO: fix _ΠT2d_integrand, and calculate the finiteT polarization for 2d if dim == 2 return Polarization0_2dZeroTemp(q, n, param) end ####################### ! temprary fix ####################################### # check sign of q, use -q if negative if q < 0 q = -q end # mink = (q < 1e-16 / minterval) ? minterval * kF : minterval * min(q, kF) # kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, maxk * kF], [0.5 * q, kF], scaleN, mink, gaussN) kgrid = finitetemp_kgrid(q, kF, maxk, scaleN, minterval, gaussN) integrand = zeros(Float64, kgrid.size) if dim == 2 for (ki, k) in enumerate(kgrid.grid) integrand[ki] = _ΠT2d_integrand(k, q, 2π * n / β, param) @assert !isnan(integrand[ki]) "nan at k=$k, q=$q" end elseif dim == 3 for (ki, k) in enumerate(kgrid.grid) integrand[ki] = _ΠT3d_integrand(k, q, 2π * n / β, param) @assert !isnan(integrand[ki]) "nan at k=$k, q=$q" end end return Interp.integrate1D(integrand, kgrid) end """ function Ladder0_FiniteTemp(q::Float64, n::AbstractVector, param, scaleN=20, minterval=1e-6, gaussN=10) Finite temperature ladder function for matsubara frequency and momentum. Analytically sum over total incoming frequency and angular dependence of momentum, and numerically calculate integration of magnitude of momentum. Assume G_0^{-1} = iω_n - (k^2/(2m) - mu) The ladder function is defined as ```math \\int \\frac{d^3 \\vec{p}}{\\left(2π^3\\right)} T \\sum_{i ω_n} \\frac{1}{iω_n+iΩ_n-\\frac{(\\vec{k}+\\vec{p})^2}{2 m}+μ} \\frac{1}{-iω_n-\\frac{p^2}{2 m}+μ} - \\frac{m}{2π^2}Λ ``` where we subtract the UV divergent term that is a constant proportional to the UV cutoff Λ. #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. Ωn=2πTn - param: other system parameters - scaleN: optional, N of Log grid in LogDensedGrid, check CompositeGrids for more detail - minterval: optional, actual minterval of grid is this value times min(q,kF) - gaussN: optional, N of GaussLegendre grid in LogDensedGrid. """ function Ladder0_FiniteTemp(q::Float64, n::AbstractVector, param; scaleN=20, minterval=1e-6, gaussN=10) @unpack dim, kF, β, me, μ = param if dim != 3 error("No support for finite-temperature polarization in $dim dimension!") end # check sign of q, use -q if negative if q < 0 q = -q end # mink = (q < 1e-16 / minterval) ? minterval * kF : minterval * min(q, kF) # kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, maxk * kF], [0.5 * q, kF], scaleN, mink, gaussN) kgrid = finitetemp_kgrid_ladder(μ, me, q, kF, scaleN, minterval, gaussN) integrand = zeros(ComplexF64, (kgrid.size, length(n))) if dim == 3 for (ki, k) in enumerate(kgrid.grid) for (mi, m) in enumerate(n) integrand[ki, mi] = _LadderT3d_integrand(k, q, 2π * m / β, param) @assert !isnan(integrand[ki, mi]) "nan at k=$k, q=$q" end end end return Interp.integrate1D(integrand, kgrid; axis=1) end """ function Polarization0_FiniteTemp(q::Float64, n::AbstractVector, param, maxk=20, scaleN=20, minterval=1e-6, gaussN=10) Finite temperature one-spin Π0 function for matsubara frequency and momentum. Analytically sum over transfer frequency and angular dependence of momentum, and numerically calculate integration of magnitude of momentum. Slower(~200μs) than Polarization0_ZeroTemp. Assume G_0^{-1} = iω_n - (k^2/(2m) - mu) #Arguments: - q: momentum - n: Matsubara frequencies given in an AbstractVector s.t. ωn=2πTn - param: other system parameters - maxk: optional, upper limit of integral -> maxk*kF - scaleN: optional, N of Log grid in LogDensedGrid, check CompositeGrids for more detail - minterval: optional, actual minterval of grid is this value times min(q,kF) - gaussN: optional, N of GaussLegendre grid in LogDensedGrid. """ function Polarization0_FiniteTemp(q::Float64, n::AbstractVector, param; maxk=20, scaleN=20, minterval=1e-6, gaussN=10) @unpack dim, kF, β = param if dim != 2 && dim != 3 error("No support for finite-temperature polarization in $dim dimension!") end # check sign of q, use -q if negative if q < 0 q = -q end # mink = (q < 1e-16 / minterval) ? minterval * kF : minterval * min(q, kF) # kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, maxk * kF], [0.5 * q, kF], scaleN, mink, gaussN) kgrid = finitetemp_kgrid(q, kF, maxk, scaleN, minterval, gaussN) integrand = zeros(Float64, (kgrid.size, length(n))) if dim == 2 for (ki, k) in enumerate(kgrid.grid) for (mi, m) in enumerate(n) integrand[ki, mi] = _ΠT2d_integrand(k, q, 2π * m / β, param) @assert !isnan(integrand[ki, mi]) "nan at k=$k, q=$q" end end elseif dim == 3 for (ki, k) in enumerate(kgrid.grid) for (mi, m) in enumerate(n) integrand[ki, mi] = _ΠT3d_integrand(k, q, 2π * m / β, param) @assert !isnan(integrand[ki, mi]) "nan at k=$k, q=$q" end end end return Interp.integrate1D(integrand, kgrid; axis=1) end """ function Polarization0_FiniteTemp!(obj::MeshArray{T,N,MT}, param; massratio=1.0, maxk=20, scaleN=20, minterval=1e-6, gaussN=10) where {T,N,MT} Store the finite-temperature one-spin Π0 function for Matsubara frequencies and momenta from `obj.mesh` within `obj.data` as specified by given parameters `param`. Analytically sum over transfer frequency and angular dependence of momentum, and numerically calculate integration of magnitude of momentum. Assume G_0^{-1} = iω_n - (k^2/(2m) - mu) #Arguments: - `obj`: MeshArray with ImFreq TemporalGrid and transfer-momentum grid (two-dimensional mesh) for polarization function. - `param`: other system parameters. `param.β` must be equal to `β` from `obj.mesh`. - `massratio`: optional, effective mass ratio. By default, `massratio=1.0`. - `maxk`: optional, upper limit of integral -> maxk*kF - `scaleN`: optional, N of Log grid in LogDensedGrid, check CompositeGrids for more detail - `minterval`: optional, actual minterval of grid is this value times min(q,kF) - `gaussN`: optional, N of GaussLegendre grid in LogDensedGrid. """ function Polarization0_FiniteTemp!(obj::MeshArray{T,N,MT}, param; massratio=1.0, maxk=20, scaleN=20, minterval=1e-6, gaussN=10) where {T,N,MT} @unpack β = param dn = GreenFunc._find_mesh(MT, ImFreq) @assert dn > 0 "No ImFreq in MeshArray for polarization." # @assert dn <= N "Dimension must be <= $N." @assert N == 2 "Polarization's mesh dimension must be 2." dk = 3 - dn @assert β ≈ obj.mesh[dn].β "Target grid has to have the same inverse temperature as param.β." for (qi, q) in enumerate(obj.mesh[dk]) if dn == 1 obj[:, qi] = Polarization0_FiniteTemp(q, obj.mesh[dn].grid, param, maxk=maxk, scaleN=scaleN, minterval=minterval, gaussN=gaussN) * massratio elseif dn == 2 obj[qi, :] = Polarization0_FiniteTemp(q, obj.mesh[dn].grid, param, maxk=maxk, scaleN=scaleN, minterval=minterval, gaussN=gaussN) * massratio end end end @inline function Polarization0_2dZeroTemp(q, n, param) @unpack me, kF, β = param density = me / 2π # check sign of q, use -q if negative if q < 0 q = -q end # if q is too small, set to 1000eps if q < eps(0.0) * 1e6 q = eps(0.0) * 1e6 end Π = 0.0 ω_n = 2 * π * n / β v = me * ω_n / q / kF * im + q / 2 / kF # v2 = me * ω_n / q / kF * im - q / 2 / kF if q < EPS && n != 0 Π = 0.0 else Π = 1.0 - real(√(v^2 - 1)) * 2kF / q # Π = 1.0 - real(√(v^2 - 1) + √(v2^2 - 1)) * kF / q end return -density * Π end @inline function Polarization0_3dZeroTemp(q, n, param) @unpack me, kF, β = param density = me * kF / (2π^2) # check sign of q, use -q if negative if q < 0 q = -q end if n < 0 n = -n end # if q is too small, set to 1000eps if q < eps(0.0) * 1e6 q = eps(0.0) * 1e6 end Π = 0.0 x = q / 2 / kF ω_n = 2 * π * n / β if n == 0 if abs(q - 2 * kF) > EPS Π = density * (1 + (1 - x^2) * log1p(4 * x / ((1 - x)^2)) / 4 / x) else Π = density end else y = me * ω_n / q / kF if abs(q - 2 * kF) > EPS if y^2 < 1e-4 / EPS theta = atan(2 * y / (y^2 + x^2 - 1)) if theta < 0 theta = theta + π end @assert theta >= 0 && theta <= π Π = density * (1 + (1 - x^2 + y^2) * log1p(4 * x / ((1 - x)^2 + y^2)) / 4 / x - y * theta) else Π = density * (2.0 / 3.0 / y^2 - 2.0 / 5.0 / y^4) #+ (6.0 - 14.0*(ω_n/4.0)^2)/21.0/y^6) end else theta = atan(2 / y) if theta < 0 theta = theta + π end @assert theta >= 0 && theta <= π Π = density * (1 + y^2 * log1p(4 / (y^2)) / 4 - y * theta) end end # initially derived for spin=1/2 return -Π / 2 end """ @inline function Polarization0_3dZeroTemp_LinearDispersion(q, n, param) Polarization for electrons with dispersion linearized near the Fermi surface. See "Condensed Matter Field Theory" by Altland, Eq. (5.30). ```math Π_{q, ω_n}=-\\frac{1}{2} N_F \\left[1-\\frac{i ω_n}{2 v_F q} \\operatorname{ln} \\left(\\frac{i ω_n+v_F q}{i ω_n-v_F q}\\right)\\right] ``` The log function can be replaced with arctan, ```math \\operatorname{arctan}(x) = \\frac{i}{2} \\ln \\frac{i+x}{i-x} ``` """ @inline function Polarization0_3dZeroTemp_LinearDispersion(q, n, param) @unpack me, kF, β = param density = me * kF / (2π^2) #spinless density of states # check sign of q, use -q if negative if q < 0 q = -q end if n < 0 n = -n end # if q is too small, set to 1000eps if q < eps(0.0) * 1e6 q = eps(0.0) * 1e6 end Π = 0.0 if n == 0 Π = density else vF = kF / me ω_n = 2 * π * n / β x = q * vF / ω_n # y = ω_n / (q * vF) if abs(x) > 1e-6 Π = density * (1 - atan(x) / x) else Π = density * (x^2 / 3 - x^4 / 5) end end # initially derived for spin=1/2 return -Π end """ @inline function Polarization0_3dZeroTemp_Q(q, n, param) Polarization for electrons ansatz inspired by "Condensed Matter Field Theory" by Altland, Problem 6.7. ```math Π(q, iω_n) = -\\frac{1}{2} N_F \\left(1-\\frac{π}\\sqrt{\\left(\\frac{2v_F q}{ω_n} \\right)^2+π^2}\\right) ``` This ansatz is asymtotically exact in the large q limit, and is only qualitatively correct in the small q limit. # Remark: For the exact free-electron polarization, we expect In the limit q ≫ ω_n, ```math Π(q, iω_n) → -\\frac{1}{2} N_F \\left(1-\\frac{π}{2}\\frac{|ω_n|}{v_F q}\\right) ``` and in the limit q ≪ ω_n, ```math Π(q, iω_n) → -\\frac{1}{2} N_F \\frac{1}{3}\\left(\\frac{v_F q}{ω_n}\\right)^2 ``` The above ansatz has the right large-q behavior, while its small-q is slightly different (prefactor 1/3 is modified to 2/π^2≈0.2026) """ @inline function Polarization0_3dZeroTemp_Q(q, n, param) @unpack me, kF, β = param density = me * kF / (2π^2) vF = kF / me # check sign of q, use -q if negative if q < 0 q = -q end if n < 0 n = -n end # if q is too small, set to 1000eps if q < eps(0.0) * 1e6 q = eps(0.0) * 1e6 end if n == 0 Π = density else Π = 0.0 ω_n = 2 * π * n / β x = q * vF / ω_n Π = density * (1 - π / sqrt(π^2 + 4 * x^2)) # Π = density * (1 - π / sqrt(π^2 + 4 * x^2 + 0.3 * abs(x))) # Π = density * (1 - π / sqrt(π^2 + 0 * x^2 + 4.0 * x^4)) # Π = density * (1 - π / sqrt(π^2 + 4 * x^2 + 0.01 * q^2 / kF^2)) end # initially derived for spin=1/2 return -Π end """ @inline function Polarization0_3dZeroTemp_Plasma(q, n, param; factor = 3.0) This polarization ansatz preserves the plasma frequency and the static limit. ```math Π(q, iω_n) = -\\frac{1}{2} \\frac{q^2}{4πe^2} \\frac{ω_p^2}{ω_n^2 + ω_p^2\\cdot (q/q_{TF})^2} = -\\frac{N_F}{2}\\left(1-\\frac{3}{3+(q \\cdot vF/ω_n)^2}\\right) ``` where ω_p is the plasma frequency, and ```math ω_p = v_F q_{TF}/\\sqrt{3} ``` User may change the parameter `factor` to modify the plasma frequency in this ansatz. """ @inline function Polarization0_3dZeroTemp_Plasma(q, n, param; factor=3.0) @unpack me, kF, β, ωp, qTF, e0, NF = param density = me * kF / (2π^2) vF = kF / me # check sign of q, use -q if negative if q < 0 q = -q end if n < 0 n = -n end # if q is too small, set to 1000eps if q < eps(0.0) * 1e6 q = eps(0.0) * 1e6 end Π = 0.0 ω_n = 2 * π * n / β x = q * vF / ω_n if n == 0 Π = density else Π = density * (x^2.0 / (factor + x^2.0)) end # initially derived for spin=1/2 return -Π end """ function Polarization0_ZeroTemp(q::Float64, n::Int, param) Zero temperature one-spin Π0 function for matsubara frequency and momentum. For low temperature the finite temperature polarization could be approximated with this function to run faster(~200ns). Assume G_0^{-1} = iω_n - (k^2/(2m) - E_F). #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. ωn=2πTn - param: other system parameters """ function Polarization0_ZeroTemp(q::Float64, n::Int, param; kwargs...) @unpack dim = param if dim == 2 return Polarization0_2dZeroTemp(q, n, param) elseif dim == 3 return Polarization0_3dZeroTemp(q, n, param) else error("No support for zero-temperature polarization in $dim dimension!") end end """ function Polarization0_ZeroTemp(q::Float64, n::AbstractVector, param) Zero temperature one-spin Π0 function for Matsubara-frequency grid `n` and momentum `q`. For low temperature the finite temperature polarization could be approximated with this function to run faster(~200ns). Assume G_0^{-1} = iω_n - (k^2/(2m) - E_F). #Arguments: - `q`: momentum - `n`: Matsubara frequencies given in a AbstractVector s.t. ωn=2πTn - `param`: other system parameters """ function Polarization0_ZeroTemp(q::Float64, n::AbstractVector, param; kwargs...) @unpack dim = param result = zeros(Float64, length(n)) if dim == 2 for (mi, m) in enumerate(n) result[mi] = Polarization0_2dZeroTemp(q, m, param) end elseif dim == 3 for (mi, m) in enumerate(n) result[mi] = Polarization0_3dZeroTemp(q, m, param) end else error("No support for zero-temperature polarization in $dim dimension!") end return result end """ function Polarization0_ZeroTemp!(obj::MeshArray{T,N,MT}, param; massratio=1.0, kwargs...) where {T,N,MT} Store the zero-temperature one-spin Π0 function for Matsubara frequencies and momenta from `obj.mesh` within `obj.data` as specified by given parameters `param`. Assume G_0^{-1} = iω_n - (k^2/(2m) - mu) #Arguments: - `obj`: MeshArray with ImFreq TemporalGrid and transfer-momentum grid (two-dimensional mesh) for polarization function. - `param`: other system parameters. `param.β` must be equal to `β` from `obj.mesh`. - `massratio`: optional, effective mass ratio. By default, `massratio=1.0`. """ function Polarization0_ZeroTemp!(obj::MeshArray{T,N,MT}, param; massratio=1.0, kwargs...) where {T,N,MT} @unpack dim, β = param dn = GreenFunc._find_mesh(MT, ImFreq) @assert dn > 0 "No ImFreq in MeshArray for polarization." # @assert dn <= N "Dimension must be <= $N." @assert N == 2 "Polarization's mesh dimension must be 2." dk = 3 - dn @assert β ≈ obj.mesh[dn].β "Target grid has to have the same inverse temperature as param.β." if dim == 2 for ind in eachindex(obj) q = obj.mesh[dk][ind[dk]] n = obj.mesh[dn].grid[ind[dn]] obj[ind] = Polarization0_2dZeroTemp(q, n, param) * massratio end elseif dim == 3 for ind in eachindex(obj) q = obj.mesh[dk][ind[dk]] n = obj.mesh[dn].grid[ind[dn]] obj[ind] = Polarization0_3dZeroTemp(q, n, param) * massratio end else error("No support for zero-temperature polarization in $dim dimension!") end end function Polarization0_ZeroTemp_Quasiparticle(q::Float64, n, param; massratio=1.0, kwargs...) return Polarization0_ZeroTemp(q, n, param; kwargs...) * massratio end """ function Polarization0wrapped(Euv, rtol, sgrid::SGT, param, pifunc = Polarization0_ZeroTemp) where{TGT, SGT} Π0 function for matsubara frequency and momentum. Use Polarization0_ZeroTemp by default, `Polarization0_ZeroTemp!` when pifunc is specified. Assume G_0^{-1} = iω_n - (k^2/(2m) - E_F). Return full polarization0 function stored in GreenFunc.MeshArray. #Arguments: - Euv: Euv of DLRGrid - rtol: rtol of DLRGrid - sgrid: momentum grid - param: other system parameters - pifunc: single point Π0 function used. Require form with pifunc(::MeshArray, param). """ function Polarization0wrapped(Euv, rtol, sgrid::SGT, param; pifunc=Polarization0_ZeroTemp!) where {SGT} @unpack β = param wn_mesh = GreenFunc.ImFreq(β, BOSON; Euv=Euv, rtol=rtol, symmetry=:ph) green = GreenFunc.MeshArray(wn_mesh, sgrid; dtype=ComplexF64) pifunc(green, param) return green end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
12104
""" Calculate self-energy """ module SelfEnergy using ..Parameter, ..Convention, ..Polarization, ..Interaction, ..LegendreInteraction using ..Parameters, ..GreenFunc, ..Lehmann, ..LegendrePolynomials, ..CompositeGrids @inline function Fock0_3dZeroTemp(k, param) @assert param.ga ≈ 0 "current implementation only supports spin-symmetric interaction" @assert param.dim == 3 @assert k >= 0 # TODO: add spin-asymmetric interaction @unpack me, kF, Λs, e0 = param if k < 1e-6 k = 1e-6 end l = sqrt(Λs) if l > 1e-14 fock = 1 + l / kF * (atan((k - kF) / l) - atan((k + kF) / l)) fock -= (l^2 - k^2 + kF^2) / 4 / k / kF * log((l^2 + (k - kF)^2) / (l^2 + (k + kF)^2)) else if abs(k - kF) > 1e-10 fock = 1 + (k^2 - kF^2) / 4 / k / kF * log((k - kF)^2 / (k + kF)^2) else fock = 1 end end return fock * (-e0^2 * kF) / π end @inline function Fock0_2dZeroTemp(k, param) @assert param.ga ≈ 0 "current implementation only supports spin-symmetric interaction" @assert param.dim == 2 # TODO: add spin-asymmetric interaction @unpack me, kF, Λs, e0 = param l2 = Λs x = √((k - kF)^2 + l2) y = √((k + kF)^2 + l2) z = √(k^2 + l2) if abs(k) > EPS if l2 < EPS fock = abs(k - kF) * (1 - kF / k) + abs(k + kF) * (1 + kF / k) - 2 * abs(k) else fock = (k - kF) * x / k + (k + kF) * y / k - 2z fock += l2 * log((k - kF + x) * (k + kF + y) / (k + z)^2) / k end else fock = 4 * (√(kF^2 + l2) - sqrt(Λs)) end return fock * (-e0^2) / 4π end # @inline function Fock0_2dZeroTemp(k, param) # @assert param.e0a ≈ 0 "current implementation only supports spin-symmetric interaction" # @assert param.dim == 2 # # TODO: add spin-asymmetric interaction # @unpack me, kF, Λs, e0 = param # @assert !(Λs ≈ 0.0) "Fock diverges diverges for the bare Coulomb interaction" # l2 = Λs # x = kF^2 + l2 - k^2 # c = 4 * k^2 * l2 # return -e0^2 * log((sqrt(x^2 + c) + x) / 2 / l2) # end """ function Fock0_ZeroTemp(q, n, param) Zero temperature one-spin Fock function for momentum. Assume G_0^{-1} = iω_n - (k^2/(2m) - E_F) and Yukawa/Coulomb instant interaction. #Arguments: - q: momentum - n: matsubara frequency given in integer s.t. ωn=2πTn - param: other system parameters """ function Fock0_ZeroTemp(k::Float64, param) @unpack dim = param if dim == 2 return Fock0_2dZeroTemp(k, param) elseif dim == 3 return Fock0_3dZeroTemp(k, param) else error("No support for zero-temperature Fock in $dim dimension!") end end function G0wrapped(Euv, rtol, sgrid, param) @unpack me, β, μ = param wn_mesh = GreenFunc.ImFreq(β, FERMION; Euv=Euv, rtol=rtol) green = GreenFunc.MeshArray(wn_mesh, sgrid; dtype=ComplexF64) for ind in eachindex(green) green[ind] = 1 / (im * wn_mesh[ind[1]] - (green.mesh[2][ind[2]]^2 / 2 / me - μ)) end return green end function Gwrapped(Σ::GreenFunc.MeshArray, Σ_ins::GreenFunc.MeshArray, param) @unpack me, kF, β, μ = param Σ_freq = Σ |> to_dlr |> to_imfreq green = similar(Σ_freq) w0i_label = locate(Σ_freq.mesh[1], 0) kf_label = locate(Σ_freq.mesh[2], kF) Σ_shift = real(Σ_freq[w0i_label, kf_label] + Σ_ins[1, kf_label]) for ind in eachindex(green) green[ind] = 1 / (im * green.mesh[1][ind[1]] - (green.mesh[2][ind[2]]^2 / 2 / me - μ) - Σ_freq[ind] - Σ_ins[1, ind[2]] + Σ_shift) end return green end function calcΣ_2d(G::GreenFunc.MeshArray, W::LegendreInteraction.DCKernel) @unpack β = W.param kgrid = W.kgrid qgrids = W.qgrids fdlr = G.mesh[1].representation bdlr = W.dlrGrid G_dlr = G |> to_dlr G_imt = G_dlr |> to_imtime # prepare kernel, interpolate into τ-space with fdlr.τ kernel_bare = W.kernel_bare kernel_freq = W.kernel kernel = Lehmann.matfreq2tau(bdlr, kernel_freq, fdlr.τ, bdlr.n; axis=3) # container of Σ Σ = GreenFunc.MeshArray(G_imt.mesh[1], kgrid; dtype=ComplexF64) # equal-time green (instant) G_ins = dlr_to_imtime(G_dlr, [β,]) * (-1) Σ_ins = GreenFunc.MeshArray(G_ins.mesh[1], kgrid; dtype=ComplexF64) for τi in eachindex(G_imt.mesh[1]) for ki in eachindex(kgrid) Gq = CompositeGrids.Interp.interp1DGrid(G_imt[τi, :], G_imt.mesh[2], qgrids[ki].grid) integrand = kernel[ki, 1:qgrids[ki].size, τi] .* Gq .* qgrids[ki].grid Σ[τi, ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) @assert isfinite(Σ[τi, ki]) "fail Δ at $τi, $ki" if τi == 1 Gq = CompositeGrids.Interp.interp1DGrid(G_ins[1, :], G_ins.mesh[2], qgrids[ki].grid) integrand = kernel_bare[ki, 1:qgrids[ki].size] .* Gq .* qgrids[ki].grid Σ_ins[1, ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) @assert isfinite(Σ_ins[1, ki]) "fail Δ0 at $ki" end end end return Σ / (-4 * π^2), Σ_ins / (-4 * π^2) end function calcΣ_3d(G::GreenFunc.MeshArray, W::LegendreInteraction.DCKernel) @unpack β = W.param kgrid = W.kgrid qgrids = W.qgrids fdlr = G.mesh[1].representation bdlr = W.dlrGrid G_dlr = G |> to_dlr G_imt = G_dlr |> to_imtime # prepare kernel, interpolate into τ-space with fdlr.τ kernel_bare = W.kernel_bare kernel_freq = W.kernel kernel = Lehmann.matfreq2tau(bdlr, kernel_freq, fdlr.τ, bdlr.n; axis=3) # container of Σ Σ = GreenFunc.MeshArray(G_imt.mesh[1], kgrid; dtype=ComplexF64) # equal-time green (instant) G_ins = dlr_to_imtime(G_dlr, [β,]) * (-1) Σ_ins = GreenFunc.MeshArray(G_ins.mesh[1], kgrid; dtype=ComplexF64) for τi in eachindex(G_imt.mesh[1]) for ki in eachindex(kgrid) k = kgrid[ki] Gq = CompositeGrids.Interp.interp1DGrid(G_imt[τi, :], G_imt.mesh[2], qgrids[ki].grid) integrand = kernel[ki, 1:qgrids[ki].size, τi] .* Gq ./ k .* qgrids[ki].grid Σ[τi, ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) @assert isfinite(Σ[τi, ki]) "fail Δ at $τi, $ki" if τi == 1 Gq = CompositeGrids.Interp.interp1DGrid(G_ins[1, :], G_ins.mesh[2], qgrids[ki].grid) integrand = kernel_bare[ki, 1:qgrids[ki].size] .* Gq ./ k .* qgrids[ki].grid Σ_ins[1, ki] = CompositeGrids.Interp.integrate1D(integrand, qgrids[ki]) @assert isfinite(Σ_ins[1, ki]) "fail Δ0 at $ki" end end end return Σ / (-4 * π^2), Σ_ins / (-4 * π^2) end function G0W0(param, Euv, rtol, Nk, maxK, minK, order, int_type, kgrid::Union{AbstractGrid,AbstractVector,Nothing}=nothing; kwargs...) @unpack dim = param # kernel = SelfEnergy.LegendreInteraction.DCKernel_old(param; # Euv = Euv, rtol = rtol, Nk = Nk, maxK = maxK, minK = minK, order = order, int_type = int_type, spin_state = :sigma) # kernel = SelfEnergy.LegendreInteraction.DCKernel0(param; # Euv = Euv, rtol = rtol, Nk = Nk, maxK = maxK, minK = minK, order = order, int_type = int_type, spin_state = :sigma) # G0 = G0wrapped(Euv, rtol, kernel.kgrid, param) kGgrid = CompositeGrid.LogDensedGrid(:cheb, [0.0, maxK], [0.0, param.kF], Nk, minK, order) if dim == 2 if isnothing(kgrid) kernel = SelfEnergy.LegendreInteraction.DCKernel_2d(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, spin_state=:sigma, kwargs...) else if (kgrid isa AbstractVector) kgrid = SimpleG.Arbitrary{eltype(kgrid)}(kgrid) end kernel = SelfEnergy.LegendreInteraction.DCKernel_2d(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, spin_state=:sigma, kgrid=kgrid, kwargs...) end G0 = G0wrapped(Euv, rtol, kGgrid, param) Σ, Σ_ins = calcΣ_2d(G0, kernel) elseif dim == 3 if isnothing(kgrid) kernel = SelfEnergy.LegendreInteraction.DCKernel0(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, spin_state=:sigma, kwargs...) else if (kgrid isa AbstractVector) kgrid = SimpleG.Arbitrary{eltype(kgrid)}(kgrid) end kernel = SelfEnergy.LegendreInteraction.DCKernel0(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, spin_state=:sigma, kgrid=kgrid, kwargs...) end G0 = G0wrapped(Euv, rtol, kGgrid, param) Σ, Σ_ins = calcΣ_3d(G0, kernel) else error("No support for G0W0 in $dim dimension!") end return Σ, Σ_ins end function G0W0(param, kgrid::Union{AbstractGrid,AbstractVector,Nothing}=nothing; Euv=100 * param.EF, rtol=1e-14, Nk=12, maxK=6 * param.kF, minK=1e-8 * param.kF, order=8, int_type=:rpa, kwargs...) return G0W0(param, Euv, rtol, Nk, maxK, minK, order, int_type, kgrid; kwargs...) end """ function zfactor(param, Σ::GreenFunc.MeshArray; kamp=param.kF, ngrid=[0, 1]) calculate the z-factor of the self-energy at the momentum kamp ```math z_k=\\frac{1}{1-\\frac{\\partial Im\\Sigma(k, 0^+)}{\\partial \\omega}} ``` """ function zfactor(param, Σ::GreenFunc.MeshArray; kamp=param.kF, ngrid=[0, 1]) @unpack kF, β = param k_label = locate(Σ.mesh[2], kamp) kamp = Σ.mesh[2][k_label] Σ_freq = dlr_to_imfreq(to_dlr(Σ), ngrid[1:2]) ΣI = imag(Σ_freq[:, k_label]) ds_dw = (ΣI[2] - ΣI[1]) / 2 / π * β Z0 = 1 / (1 - ds_dw) return Z0, kamp end """ function massratio(param, Σ::GreenFunc.MeshArray, Σ_ins::GreenFunc.MeshArray, δK=5e-6; kamp=param.kF) calculate the effective mass of the self-energy at the momentum kamp ```math \\frac{m^*_k}{m}=\\frac{1}{z_k} \\cdot \\left(1+\\frac{m}{k}\\frac{\\partial Re\\Sigma(k, 0)}{\\partial k}\\right)^{-1} ``` """ function massratio(param, Σ::GreenFunc.MeshArray, Σ_ins::GreenFunc.MeshArray, δK=5e-6; kamp=param.kF) # one can achieve ~1e-5 accuracy with δK = 5e-6 @unpack kF, me = param δK *= kF k_label = locate(Σ.mesh[2], kamp) kamp = Σ.mesh[2][k_label] z = zfactor(param, Σ; kamp=kamp)[1] Σ_freq = dlr_to_imfreq(to_dlr(Σ), [0, 1]) k1, k2 = k_label, k_label + 1 while abs(Σ.mesh[2][k2] - Σ.mesh[2][k1]) < δK k2 += 1 end # @assert kF < kgrid.grid[k1] < kgrid.grid[k2] "k1 and k2 are not on the same side! It breaks $kF > $(kgrid.grid[k1]) > $(kgrid.grid[k2])" sigma1 = real(Σ_freq[1, k1] + Σ_ins[1, k1]) sigma2 = real(Σ_freq[1, k2] + Σ_ins[1, k2]) ds_dk = (sigma1 - sigma2) / (Σ.mesh[2][k1] - Σ.mesh[2][k2]) return 1.0 / z / (1 + me / kamp * ds_dk), kamp end """ function bandmassratio(param, Σ::GreenFunc.MeshArray, Σ_ins::GreenFunc.MeshArray; kamp=param.kF) calculate the effective band mass of the self-energy at the momentum kamp ```math \\frac{m^*_k}{m}=\\frac{1}{z_k}\\cdot \\left(1+\\frac{Re\\Sigma(k, 0) - Re\\Sigma(0, 0)}{k^2/2m}\\right)^{-1} ``` """ function bandmassratio(param, Σ::GreenFunc.MeshArray, Σ_ins::GreenFunc.MeshArray; kamp=param.kF) # one can achieve ~1e-5 accuracy with δK = 5e-6 @unpack me = param z = zfactor(param, Σ; kamp=kamp)[1] k_label = locate(Σ.mesh[2], kamp) kamp = Σ.mesh[2][k_label] Σ_freq = dlr_to_imfreq(to_dlr(Σ), [0, 1]) sigma1 = real(Σ_freq[1, k_label] + Σ_ins[1, k_label]) sigma2 = real(Σ_freq[1, 1] + Σ_ins[1, 1]) ds_dk = (sigma1 - sigma2) / (kamp^2 / 2 / me) return 1.0 / z / (1 + ds_dk), kamp end function chemicalpotential(param, Σ::GreenFunc.MeshArray, Σ_ins::GreenFunc.MeshArray) # one can achieve ~1e-5 accuracy with δK = 5e-6 @unpack kF, me = param k_label = locate(Σ.mesh[2], kF) Σ_freq = dlr_to_imfreq(to_dlr(Σ), [-1, 0]) return real(Σ_freq[1, k_label] + Σ_ins[1, k_label]) end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
6307
""" Provide N-body response and correlation functions """ module TwoPoint export freePropagatorT, freePropagatorΩ export freePolarizationT using Lehmann using Cuba """ freePropagatorT(type, τ, ω, β) Imaginary-time propagator. # Arguments - `type`: symbol :fermi, :bose - `τ`: the imaginary time, must be (-β, β] - `ω`: dispersion ϵ_k-μ - `β = 1.0`: the inverse temperature """ @inline function freePropagatorT(type, τ, ω, β) return kernelT(type, τ, ω, β) end """ freePropagatorΩ(type, n, ω, β=1.0) Matsubara-frequency kernel of different type # Arguments - `type`: symbol :fermi, :bose, :corr - `n`: index of the Matsubara frequency - `ω`: dispersion ϵ_k-μ - `β`: the inverse temperature """ @inline function freePropagatorΩ(type, n::Int, ω, β) return kernelΩ(type, n, ω, β) end @inline function freeFermiDoS(dim, kF, m, spin) if dim == 3 return spin * m * kF / 2 / π^2 else error("Dimension $dim not implemented!") # return spin/4/π end end # function LindhardΩn(dim, q, ω, β, kF, m, spin) # q < 0.0 && (q = -q) # Lindhard function is q symmetric # q2 = q^2 # kFq = 2kF * q # ωn = 2π * n / β # D = 1 / (8kF * q) # NF = freeFermiDoS(dim, kF, m, spin) # # if ωn<=20*(q2+kFq)/(2m) # # careful for small q or large w # iw = ωn * im # wmq2 = iw * 2m - q^2 # wpq2 = iw * 2m + q^2 # C1 = log(wmq2 - kFq) - log(wmq2 + kFq) # C2 = log(wpq2 - kFq) - log(wpq2 + kFq) # res = real(-NF / 2 * (1 - D * (wmq2^2 / q^2 - 4 * kF^2) * C1 + D * (wpq2^2 / q^2 - 4 * kF^2) * C2)) # # else # # b2 = q2 * ( q2 + 12/5 * kF^2 ) # # c = 2*EF*kF*q2/(3*pi**2) # # res = -c/(w**2 + b2) # # end # return res # end """ LindhardΩnFiniteTemperature(dim::Int, q::T, n::Int, μ::T, kF::T, β::T, m::T, spin) where {T <: AbstractFloat} Compute the polarization function of free electrons at a given frequency. Relative Accuracy is about ~ 1e-6 # Arguments - `dim`: dimension - `q`: external momentum, q<1e-4 will be treated as q=0 - `n`: externel Matsubara frequency, ωn=2π*n/β - `μ`: chemical potential - `kF`: Fermi momentum - `β`: inverse temperature - `m`: mass - `spin` : number of spins """ @inline function LindhardΩnFiniteTemperature(dim::Int, q::T, n::Int, μ::T, kF::T, β::T, m::T, spin) where {T<:AbstractFloat} if q < 0.0 q = -q end if q / kF < 1.0e-10 q = 1.0e-10 * kF end function polar(k) phase = T(1.0) if dim == 3 phase *= k^2 / (4π^2) else error("not implemented") end ω = 2π * n / β ϵ = (k^2 - μ) / (2m) p = phase * Spectral.fermiDirac(ϵ, β) * m / k / q * log(((q^2 - 2k * q)^2 + 4m^2 * ω^2) / ((q^2 + 2k * q)^2 + 4m^2 * ω^2)) * spin if isnan(p) println("warning: integrand at ω=$ω, q=$q, k=$k is NaN!") end # println(p) return p end function integrand(x, f) # x[1]:k f[1] = polar(x[1] / (1 - x[1])) / (1 - x[1])^2 end # TODO: use CompositeGrids to perform the integration result, err = Cuba.cuhre(integrand, 2, 1, rtol = 1.0e-10) # result, err = Cuba.vegas(integrand, 1, 1, rtol=rtol) return result[1], err[1] end """ 3D Imaginary-time effective interaction derived from random phase approximation. Return ``dW_0(q, τ)/v_q`` where ``v_q`` is the bare Coulomb interaction and ``dW_0`` is the dynamic part of the effective interaction. The total effective interaction can be recoverd using, ```math W_0(q, τ) = v_q δ(τ) + dW_0(q, τ). ``` The dynamic contribution is the fourier transform of, ```math dW_0(q, iω_n)=v_q^2 Π(q, iω_n)/(1-v_q Π(q, iω_n)) ``` Note that this dynamic contribution ``dW_0'' diverges at small q. For this reason, this function returns ``dW_0/v_q`` # Arguments - `vqinv`: inverse bare interaction as a function of q - `qgrid`: one-dimensional array of the external momentum q - `τgrid`: one-dimensional array of the imaginary-time - `dim`: dimension - `μ`: chemical potential - `kF`: Fermi momentum - `β`: inverse temperature - `spin` : number of spins - `mass`: mass """ function dWRPA(vqinv, qgrid, τgrid, dim, μ, kF, β, spin, mass) # @assert all(qgrid .!= 0.0) EF = kF^2 / (2mass) dlr = DLRGrid(Euv = 10EF, β = β, rtol = 1e-10, isFermi = false, symmetry = :ph) # effective interaction is a correlation function of the form <O(τ)O(0)> Nq, Nτ = length(qgrid), length(τgrid) Π = zeros(Complex{Float64}, (Nq, dlr.size)) # Matsubara grid is the optimized sparse DLR grid dW0norm = similar(Π) for (ni, n) in enumerate(dlr.n) for (qi, q) in enumerate(qgrid) Π[qi, ni] = LindhardΩnFiniteTemperature(dim, q, n, μ, kF, β, mass, spin)[1] end dW0norm[:, ni] = @. Π[:, ni] / (vqinv - Π[:, ni]) # println("ω_n=2π/β*$(n), Π(q=0, n=0)=$(Π[1, ni])") # println("$ni $(dW0norm[2, ni])") end # display(dW0norm) dW0norm = matfreq2tau(dlr, dW0norm, τgrid, axis = 2) # dW0/vq in imaginary-time representation, real-valued but in complex format # println(dW0norm[1, :]) # println(DLR.matfreq2tau(:corr, dW0norm[1, :], dlr, τgrid, axis=1)) # println(DLR.matfreq2tau(:corr, dW0norm[2, :], dlr, τgrid, axis=1)) # coeff = DLR.matfreq2dlr(:corr, dW0norm[1, :], dlr) # fitted = DLR.dlr2matfreq(:corr, coeff, dlr, dlr.n) # for (ni, n) in enumerate(dlr.n) # println(dW0norm[1, ni], " vs ", fitted[ni]) # end return real.(dW0norm) end function interactionDynamic(config, qd, τIn, τOut) para = config.para dτ = abs(τOut - τIn) kDiQ = sqrt(dot(qd, qd)) vd = 4π * e0^2 / (kDiQ^2 + mass2) if kDiQ <= para.qgrid.grid[1] q = para.qgrid.grid[1] + 1.0e-6 wd = vd * Grid.linear2D(para.dW0, para.qgrid, para.τgrid, q, dτ) # the current interpolation vanishes at q=0, which needs to be corrected! else wd = vd * Grid.linear2D(para.dW0, para.qgrid, para.τgrid, kDiQ, dτ) # dynamic interaction, don't forget the singular factor vq end return vd / β, wd end function vertexDynamic(config, qd, qe, τIn, τOut) vd, wd = interactionDynamic(config, qd, τIn, τOut) ve, we = interactionDynamic(config, qe, τIn, τOut) return -vd, -wd, ve, we end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
1146
@testset "Bethe-Slapter equation" begin @testset "Cooper-pair linear response in 3D" begin dim, θ, rs = 3, 1e-2, 2.0 param = Parameter.rydbergUnit(θ, rs, dim) channel = 0 lamu, R_freq, F_freq = BSeq.linearResponse(param, channel; Ntherm=50) @test isapprox(lamu, -2.34540, rtol=1e-4) # lamu, R_freq = BSeq.linearResponse(param, 1) # @test isapprox(lamu, -1.23815, rtol=1e-5) # test stop condition. When SC, converge to 0.0 dim, θ, rs = 3, 1 / 3200, 7.0 param = Parameter.rydbergUnit(θ, rs, dim) channel = 0 lamu, R_freq, F_freq = BSeq.linearResponse(param, channel) @test isapprox(lamu, 0.0, rtol=1e-10, atol=1e-10) end # @testset "Cooper-pair linear response in 2D" begin # dim, θ, rs = 2, 1e-2, 1.5 # param = Parameter.rydbergUnit(θ, rs, dim) # channel = 0 # lamu, R_freq = BSeq.linearResponse(param, channel) # @test isapprox(lamu, -1.60555, rtol=1e-5) # lamu, R_freq = BSeq.linearResponse(param, 1) # @test isapprox(lamu, -1.05989, rtol=1e-5) # end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
2595
using MCIntegration using ElectronGas const k0, p0 = 1.000000000017037, 1.0000000000422837 param = LegendreInteraction.Parameter.defaultUnit(1e-4, 1.0, dim = 2) const e0 = param.e0 # Define the integrand function integrand(config) #config.var is a tuple of variable types specified in the second argument of `MCIntegration.Configuration(...)` X = config.var[1] x = cos(X[1]) q2 = (k0 - p0)^2 + 2k0 * p0 * (1 - x) if x == 1 || q2 <= 0 q2 = (k0 - p0)^2 + k0 * p0 * (X[1])^2 end if config.curr == 1 #config.curr is the index of the currently sampled integral by MC # return 4π / sqrt(q2) return 4π * e0^2 / sqrt(q2) end end # Define how to measure the observable function measure(config) factor = 1.0 / config.reweight[config.curr] weight = integrand(config) config.observable[config.curr] += weight / abs(weight) * factor #note that config.observable is an array with two elements as discussed below end # MC step of each block const blockStep = 1e7 # Define the types variables, the first argument sets the range, the second argument gives the largest change to the variable in one MC update. see the section [variable](#variable) for more details. T = MCIntegration.Continuous([0.0, π], 0.5) # Define how many (degrees of freedom) variables of each type. # For example, [[n1, n2], [m1, m2], ...] means the first integral involves n1 varibales of type 1, and n2 variables of type2, while the second integral involves m1 variables of type 1 and m2 variables of type 2. dof = [[1],] # Define the container for the observable. It must be a number or an array-like object. In this case, the observable has two elements, corresponds to the results for the two integrals. obs = [0.0,] # Define the configuration struct which is container of all kinds of internal data for MC, # the second argument is a tuple listing all types of variables, one then specify the degrees of freedom of each variable type in the third argument. config = MCIntegration.Configuration(blockStep, (T,), dof, obs) # perform MC integration. Nblock is the number of independent blocks to estimate the error bar. In MPI mode, the blocks will be sent to different workers. Set "print=n" to control the level of information to print. avg, err = MCIntegration.sample(config, integrand, measure; Nblock = 64, print = 1) #avg, err are the same shape as obs. In MPI mode, only the root node return meaningful estimates. All other workers simply return nothing if isnothing(avg) == false println("bare kernel: $(avg[1]) +- $(err[1]) (exact: )") end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
2399
@testset "Interaction" begin beta = 400 rs = 4.0 param = Parameter.defaultUnit(1 / beta, rs) @testset "bubble dyson" begin @test Interaction.coulombinv(0.0, Parameter.derive(param, gs=0.0, ga=0.0, Λs=0.0, Λa=0.0)) == (Inf, Inf) @test Interaction.coulomb(0.0, Parameter.derive(param, gs=0.0, ga=0.0, Λs=0.0, Λa=0.0)) == (0.0, 0.0) @test Interaction.coulombinv(0.0, Parameter.derive(param, ga=1.0, Λs=0.0, Λa=0.0)) == (0.0, 0.0) @test Interaction.coulomb(0.0, Parameter.derive(param, ga=1.0, Λs=0.0, Λa=0.0)) == (Inf, Inf) @test Interaction.coulombinv(1.0, Parameter.derive(param, gs=0.0, ga=0.0, Λs=0.0, Λa=0.0)) == (Inf, Inf) @test Interaction.coulomb(1.0, Parameter.derive(param, gs=0.0, ga=0.0, Λs=0.0, Λa=0.0)) == (0.0, 0.0) @test Interaction.bubbledyson(Inf, 1.0, 1.0) == 0.5 @test Interaction.bubbledyson(Inf, 0.0, 1.0) == 0.0 @test Interaction.bubbledyson(0.0, 1.0, 1.0) == -Inf @test Interaction.bubbledyson(0.0, 0.0, 1.0) == -Inf end @testset "RPA and KO" begin testq = [-1.0, 0.0, 1e-160, 1e-8, 0.5, 1.0, 2.0, 10.0] val = Interaction.RPA(1.0, 1, param)[1] / Interaction.coulomb(1.0, param)[1] @test isapprox(Interaction.RPA(1.0, 1, param; regular=true)[1], val, rtol=1e-10) println(Interaction.KO(1.0, 1, param)) for q in testq println(Interaction.RPA(q, 1, param; regular=true)) end println(Interaction.KO(1.0, 1, param; regular=true)) # println(Interaction.RPA(1.0, 1, param; pifunc = Interaction.Polarization.Polarization0_FiniteTemp)) # println(Interaction.KO(1.0, 1, param; pifunc = Interaction.Polarization.Polarization0_FiniteTemp)) RPA_dyn, RPA_ins = Interaction.RPAwrapped(100 * param.EF, 1e-8, [1e-8, 0.5, 1.0, 2.0, 10.0], param) show(RPA_dyn) show(RPA_ins) # println(RPA_dyn[1, :, :]) # println(RPA_dyn[2, :, :]) # println(RPA_ins[1, :, :]) # println(RPA_ins[2, :, :]) KO_dyn, KO_ins = Interaction.KOwrapped(100 * param.EF, 1e-8, [1e-8, 0.5, 1.0, 2.0, 10.0], param) show(KO_dyn) show(KO_ins) # println(KO_dyn[1, :, :]) # println(KO_dyn[2, :, :]) # println(KO_ins[1, :, :]) # println(KO_ins[2, :, :]) F_s = Interaction.landauParameterMoroni(1.0, 0, param) end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
1270
using MCIntegration using ElectronGas const para = Parameter.rydbergUnit(1.0 / 10, 4.0, 3) const n = 0 const k = 0.1 * para.kF function integrand(vars, config) n, k, para = config.userdata β, me, μ = para.β, para.me, para.μ # f(k) = 1.0 / (exp(β * (k^2 / 2 / me - μ)) + 1) function f(ek) ek = β * ek if ek > 0.0 return exp(-ek) / (exp(-ek) + 1) else return 1.0 / (exp(ek) + 1) end end x, θ = vars[1][1], vars[2][1] p = x / (1 - x) freq = n * 2π / β * 1im factor = 1 / (2π)^2 * sin(θ) * p^2 / (1 - x)^2 Ekp = (k^2 + p^2 + 2 * k * p * cos(θ)) / 2 / me - μ Ep = p^2 / 2 / me - μ w = (f(Ekp) - f(-Ep)) / (freq - Ekp - Ep) - me / p^2 if isfinite(w) && isfinite(factor) return w * factor #return 0.0 + imag(w * factor) * 1im else return 0.0 * 1im end end function ladder(n::Int, k::Float64, para) return integrate(integrand; # var=(Continuous(2 * para.kF, 1000 * para.kF), Continuous(0.0, π * 1.0)), var=(Continuous(0.0, 1.0 - 1e-6), Continuous(0.0, π * 1.0)), dof=[[1, 1],], userdata=(n, k, para), type=ComplexF64, print=1, neval=1e6 ) end println(ladder(n, k, para))
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
4995
@testset "LegendreInteraction" begin beta = 1e5 # set parameters param = LegendreInteraction.Parameter.defaultUnit(1 / beta, 1.0) kF = param.kF Nk, minK, order, maxK = 16, 1e-8, 6, 10.0 # print(param) @testset "Helper function" begin println("Test helper function") # test helper function # test with known result: bare coulomb interaction H1 = LegendreInteraction.helper_function( 1.0, 1, u -> LegendreInteraction.interaction_instant(u, param, :sigma), param; Nk=Nk, minK=minK, order=order ) H2 = LegendreInteraction.helper_function( 2.0, 1, u -> LegendreInteraction.interaction_instant(u, param, :sigma), param; Nk=Nk, minK=minK, order=order ) # println("$(H2-H1) == $(4*π*param.e0^2*log(2))") @test isapprox(H2 - H1, 4 * π * param.e0^2 * log(2), rtol=1e-4) helper_grid = CompositeGrid.LogDensedGrid(:cheb, [0.0, 2.1 * maxK], [0.0, 2kF], 4, 0.001, 4) intgrid = CompositeGrid.LogDensedGrid(:cheb, [0.0, helper_grid[end]], [0.0, 2kF], 2Nk, 0.01minK, 2order) helper = LegendreInteraction.helper_function_grid(helper_grid, intgrid, 1, u -> LegendreInteraction.interaction_instant(u, param, :sigma), param) helper_analytic = (4 * π * param.e0^2) .* log.(helper_grid.grid) helper_old = zeros(Float64, helper_grid.size) for (yi, y) in enumerate(helper_grid) helper_old[yi] = LegendreInteraction.helper_function(y, 1, u -> LegendreInteraction.interaction_instant(u, param, :sigma), param) end # println(helper .- helper[1]) # println(helper_old .- helper_old[1]) # println(helper_analytic .- helper_analytic[1]) rtol = 1e-6 for (yi, y) in enumerate(helper_grid) @test isapprox(helper[yi] - helper[1], helper_analytic[yi] - helper_analytic[1], rtol=rtol) @test isapprox(helper_old[yi] - helper_old[1], helper_analytic[yi] - helper_analytic[1], rtol=rtol) end end @testset "DCKernel_2d" begin println("Test DCKernel_2d") # set parameters param = LegendreInteraction.Parameter.defaultUnit(1 / beta, 1.0, dim=2) kF = param.kF println("kF = $kF") Euv, rtol = 100 * param.EF, 1e-10 Nk, minK, order, maxK = 8, 1e-7kF, 8, 10kF # Euv, rtol = 100 * param.EF, 1e-12 # maxK, minK = 20param.kF, 1e-9param.kF # Nk, order = 16, 6 int_type = :rpa W = LegendreInteraction.DCKernel_2d(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type, spin_state=:sigma) fdlr = ElectronGas.Lehmann.DLRGrid(Euv, param.β, rtol, true, :pha) bdlr = W.dlrGrid kgrid = W.kgrid qgrids = W.qgrids kernel_bare = W.kernel_bare kernel_freq = W.kernel kernel = real(ElectronGas.Lehmann.matfreq2tau(bdlr, kernel_freq, fdlr.τ, bdlr.n; axis=3)) kF_label = searchsortedfirst(kgrid.grid, kF) qF_label = searchsortedfirst(qgrids[kF_label].grid, kF) println("static kernel at (kF, kF): $(kgrid.grid[kF_label]), $(qgrids[kF_label].grid[qF_label])") println("$(kernel_bare[kF_label, qF_label])") # println(kernel_bare[kF_label, :]) @test isapprox(kernel_bare[kF_label, qF_label], 284, rtol=0.04) println("dynamic kernel at (kF, kF):") println(view(kernel, kF_label, qF_label, :)) end @testset "Test case: r_s=4, β=400, 3D" begin println("Test 3D, rs=4, beta=400") param = Parameter.defaultUnit(1 / beta, 4.0) # 3D UEG Euv, rtol = 100 * param.EF, 1e-12 maxK, minK = 20param.kF, 1e-9param.kF Nk, order = 16, 6 int_type = :rpa #--- prepare kernel --- W = LegendreInteraction.DCKernel0(param; Euv=Euv, rtol=rtol, Nk=Nk, maxK=maxK, minK=minK, order=order, int_type=int_type) fdlr = ElectronGas.Lehmann.DLRGrid(Euv, param.β, rtol, true, :pha) bdlr = W.dlrGrid kgrid = W.kgrid qgrids = W.qgrids kernel_bare = W.kernel_bare kernel_freq = W.kernel kernel = real(ElectronGas.Lehmann.matfreq2tau(bdlr, kernel_freq, fdlr.τ, bdlr.n; axis=3)) kF_label = searchsortedfirst(kgrid.grid, param.kF) qF_label = searchsortedfirst(qgrids[kF_label].grid, param.kF) k, p = kgrid.grid[kF_label], qgrids[kF_label].grid[qF_label] w0 = 4π * param.e0^2 * log((k + p) / abs(k - p)) / k / p println("static kernel at (kF, kF): $k, $p") println("$(kernel_bare[kF_label, qF_label]), Analytic: $w0") @test isapprox(kernel_bare[kF_label, qF_label], w0, rtol=1e-6) # @test isapprox(kernel_bare[kF_label, qF_label], 1314.5721928, rtol = 1e-6) # println(kernel_bare[kF_label, :]) println("dynamic kernel at (kF, kF):") println(view(kernel, kF_label, qF_label, :)) end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
838
@testset "Parameter" begin # test constructor and reconstruct of Para beta = 1e4 rs = 2.0 param = Parameter.defaultUnit(1 / beta, rs) @test param.me == 0.5 @test param.EF == 1.0 @test param.kF == 1.0 @test param.β == beta @test param.gs == 1.0 @test param.ga == 0.0 @test param.ωp ≈ sqrt(4 * param.kF^3 * param.e0^2 / 3 / param.me / π) @test param.qTF ≈ sqrt(4 * π * param.e0^2 * param.NF) newbeta = 1e3 ga = 1.0 newparam = Parameter.derive(param, β=newbeta, ga=ga) @test newparam.me == 0.5 @test newparam.EF == 1.0 @test newparam.kF == 1.0 @test newparam.β == newbeta @test newparam.ga == ga @test newparam.ωp ≈ sqrt(4 * newparam.kF^3 * newparam.e0^2 / 3 / newparam.me / π) @test newparam.qTF ≈ sqrt(4 * π * newparam.e0^2 * newparam.NF) end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
3651
# using Gaston @testset "Polarization" begin beta, rs = 1e8, 1.0 param3d = Parameter.defaultUnit(1 / beta, rs, 3) param2d = Parameter.defaultUnit(1 / beta, rs, 2) @testset "Polarization: ZeroTemp vs. FiniteTemp" begin # for low temp, Π from zero temp and finite temp should be close qgrid = [-1.0, 0.0, 1e-16, 1e-8, 1e-7, 1e-6, 1e-5, 5e-5, 1e-4, 1e-3, 0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 3.0] ngrid = [n for n in -5:20] for (qi, q) in enumerate(qgrid) for (ni, n) in enumerate(ngrid) # println("q=$q, n=$n") @test isapprox( Polarization.Polarization0_ZeroTemp(q, n, param3d), Polarization.Polarization0_FiniteTemp(q, n, param3d), rtol=1e-6 ) end end for (qi, q) in enumerate(qgrid) for (ni, n) in enumerate(ngrid) @test isapprox( Polarization.Polarization0_ZeroTemp(q, n, param2d), Polarization.Polarization0_FiniteTemp(q, n, param2d), rtol=1e-4 ) end end end qgrid = [-1.0, 0.0, 1e-16, 1e-8, 1e-7, 1e-6, 1e-5, 5e-5, 1e-4, 1e-3, 0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 3.0] ngrid = [n for n in -5:20] @testset "Polarization0!: 3D ZeroTemp vs. FiniteTemp" begin # param = Parameter.defaultUnit(1 / beta, rs, 3) nmesh = MeshGrids.ImFreq(param3d.β, BOSON; grid=ngrid) PZ = MeshArray(nmesh, qgrid; dtype=Float64) PF = similar(PZ) Polarization.Polarization0_ZeroTemp!(PZ, param3d) Polarization.Polarization0_FiniteTemp!(PF, param3d) for ind in eachindex(PZ) @test isapprox(PZ[ind], PF[ind], rtol=1e-6) end end @testset "Polarization: wrapped" begin PZ = Polarization.Polarization0wrapped(100param3d.EF, 1e-10, qgrid, param3d, pifunc=Polarization.Polarization0_ZeroTemp!) PF = Polarization.Polarization0wrapped(100param3d.EF, 1e-10, qgrid, param3d, pifunc=Polarization.Polarization0_FiniteTemp!) PZ = Polarization.Polarization0wrapped(100param2d.EF, 1e-10, qgrid, param2d, pifunc=Polarization.Polarization0_ZeroTemp!) # PZ = Polarization.Polarization0wrapped(100param.EF, 1e-10, qgrid, param, pifunc=Polarization.Polarization0_ZeroTemp) # PF = Polarization.Polarization0wrapped(100param.EF, 1e-10, qgrid, param, pifunc=Polarization.Polarization0_FiniteTemp) end @testset "Ladder" begin para = Parameter.rydbergUnit(1.0 / 10, 4.0, 3) ladder = Polarization.Ladder0_FiniteTemp(0.1 * para.kF, 1, para, gaussN=16, minterval=1e-8) @test abs(real(ladder) - 0.0053666) < 3 * 1.7e-5 @test abs(imag(ladder) - 0.006460) < 3 * 1.1e-5 ladder = Polarization.Ladder0_FiniteTemp(0.1 * para.kF, 0, para, gaussN=16, minterval=1e-8) #zero frequency @test abs(real(ladder) - 0.021199) < 3 * 2.0e-5 @test abs(imag(ladder) - 0.0) < 3 * 3.3e-11 end # while true # print("Please enter a whole number between 1 and 5: ") # input = readline(stdin) # value = tryparse(Int, input) # if value !== nothing && 1 <= value <= 5 # println("You entered $(input)") # break # else # @warn "Enter a whole number between 1 and 5" # end # end # plt = plot(qgrid, polar, ytics = -0.08:0.01, ls = 1, Axes(grid = :on, key = "left")) # display(plt) # save(term = "png", output = "polar_2d.png", # saveopts = "font 'Consolas,10' size 1280,900 lw 1") end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
408
using ElectronGas using CompositeGrids using Test using GreenFunc, Lehmann @testset "ElectronGas.jl" begin # Write your tests here. if isempty(ARGS) include("parameter.jl") include("polarization.jl") include("interaction.jl") include("legendreinteraction.jl") include("selfenergy.jl") include("BSeq.jl") else include(ARGS[1]) end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
code
7836
@testset "Self Energy" begin @testset "3D Fock" begin θ, rs = 0.1, 1.0 para = Parameter.rydbergUnit(θ, rs, 3) println("$(para.μ), $(para.EF)") factor = -para.e0^2 * para.kF / π #test edge case when k → 0 @test isapprox(SelfEnergy.Fock0_ZeroTemp(0.0, para) / factor, 2.0, rtol=1e-6) @test isapprox(SelfEnergy.Fock0_ZeroTemp(1e-6, para) / factor, 2.0, rtol=1e-6) #test edge case when k → 0 @test isapprox(SelfEnergy.Fock0_ZeroTemp(para.kF, para) / factor, 1.0, rtol=1e-6) @test isapprox(SelfEnergy.Fock0_ZeroTemp(para.kF + 1e-7, para) / factor, 1.0, rtol=1e-6) @test isapprox(SelfEnergy.Fock0_ZeroTemp(para.kF - 1e-7, para) / factor, 1.0, rtol=1e-6) #test edge case when Λs → 0 para = Parameter.rydbergUnit(θ, rs, 3, Λs=1e-12) @test isapprox(SelfEnergy.Fock0_ZeroTemp(0.0, para) / factor, 2.0, rtol=1e-6) end @testset "2D Fock" begin θ, rs = 0.1, 1.0 para = Parameter.rydbergUnit(θ, rs, 2, Λs=0.1) println("$(para.μ), $(para.EF)") #test edge case when k → 0 f1 = SelfEnergy.Fock0_ZeroTemp(0.0, para) f2 = SelfEnergy.Fock0_ZeroTemp(1e-7, para) @test isapprox(f1, f2, rtol=1e-6) para1 = Parameter.rydbergUnit(θ, rs, 2) para2 = Parameter.rydbergUnit(θ, rs, 2, Λs=1e-12) @test isapprox(SelfEnergy.Fock0_ZeroTemp(para1.kF, para1), SelfEnergy.Fock0_ZeroTemp(para2.kF, para2), rtol=1e-6) end @testset "RPA based on the user-defined kgrid" begin θ, rs = 0.01, 4.0 para = Parameter.rydbergUnit(θ, rs, 3, Λs=1e-5) sigma1 = SelfEnergy.G0W0(para) kFidx = locate(sigma1[1].mesh[2], para.kF) sigma2 = SelfEnergy.G0W0(para, [sigma1[1].mesh[2][kFidx],]) @test isapprox(sigma1[1][1, kFidx], sigma2[1][1, 1], rtol=1e-6) @test isapprox(sigma1[2][1, kFidx], sigma2[2][1, 1], rtol=1e-6) para = Parameter.rydbergUnit(θ, rs, 2, Λs=1e-5) sigma1 = SelfEnergy.G0W0(para) kFidx = locate(sigma1[1].mesh[2], para.kF) sigma2 = SelfEnergy.G0W0(para, [sigma1[1].mesh[2][kFidx],]) @test isapprox(sigma1[1][1, kFidx], sigma2[1][1, 1], rtol=1e-6) @test isapprox(sigma1[2][1, kFidx], sigma2[2][1, 1], rtol=1e-6) end @testset "3D RPA" begin # make sure everything works for different unit sets θ = 0.001 # rslist = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] # zlist = [0.859, 0.764, 0.700, 0.645, 0.602, 0.568] # mlist = [0.970, 0.992, 1.016, 1.039, 1.059, 1.078] ## our results: zlist = [0.859, 0.764, 0.693, 0.637, 0.591] # rslist = [5.0,] # zlist = [0.5913,] # mlist = [1.059,] # rslist = [1.0, 2.0] # zlist = [0.859, 0.764] # mlist = [0.970, 0.992] rslist = [2.0,] zlist = [0.764,] mlist = [0.992,] for (ind, rs) in enumerate(rslist) param = Parameter.rydbergUnit(θ, rs) kF, β = param.kF, param.β Euv, rtol = 1000 * param.EF, 1e-11 # Nk, order = 8, 4 # maxK, minK = 10kF, 1e-7kF # Nk, order = 11, 8 maxK, minK = 20kF, 1e-8kF Nk, order = 12, 8 # maxK, minK = 10kF, 1e-9kF # Euv, rtol = 1000 * param.EF, 1e-11 # maxK, minK = 20param.kF, 1e-9param.kF # Nk, order = 16, 12 kgrid = CompositeGrid.LogDensedGrid(:gauss, [0.0, maxK], [0.0, kF], Nk, minK, order) # test G0 G0 = SelfEnergy.G0wrapped(Euv, rtol, kgrid, param) # kF_label = searchsortedfirst(kgrid.grid, kF) kF_label = locate(G0.mesh[2], kF) G0_dlr = G0 |> to_dlr G0_tau = G0_dlr |> to_imtime G0_ins = dlr_to_imtime(G0_dlr, [β,]) * (-1) integrand = real(G0_ins[1, :]) .* kgrid.grid .* kgrid.grid density0 = CompositeGrids.Interp.integrate1D(integrand, kgrid) / π^2 @test isapprox(param.n, density0, rtol=3e-5) @time Σ, Σ_ins = SelfEnergy.G0W0(param, Euv, rtol, Nk, maxK, minK, order, :rpa) Z0 = (SelfEnergy.zfactor(param, Σ))[1] z = zlist[ind] @test isapprox(Z0, z, rtol=3e-3) mratio = SelfEnergy.massratio(param, Σ, Σ_ins)[1] mratio1 = SelfEnergy.massratio(param, Σ, Σ_ins, 1e-5)[1] m = mlist[ind] @test isapprox(mratio, m, rtol=3e-3) @test isapprox(mratio, mratio1, rtol=1e-4) println("θ = $θ, rs= $rs") println("Z-factor = $Z0 ($z), rtol=$(Z0/z-1)") println("m*/m = $mratio ($m), rtol=$(mratio/m-1)") ## test G_RPA G = SelfEnergy.Gwrapped(Σ, Σ_ins, param) G_dlr = G |> to_dlr G_tau = G_dlr |> to_imtime G_ins = dlr_to_imtime(G_dlr, [β,]) * (-1) integrand = real(G_ins[1, :]) .* kgrid.grid .* kgrid.grid density = CompositeGrids.Interp.integrate1D(integrand, kgrid) / π^2 @test isapprox(param.n, density, rtol=5e-3) println("density n, from G0, from G_RPA: $(param.n), $density0 (rtol=$(density0/param.n-1)), $density (rtol=$(density/param.n-1))") end end @testset "2D RPA" begin dim = 2 θ = 1e-5 # rslist = [0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 8.0, 10.0] # zlist = [0.786, 0.662, 0.519, 0.437, 0.383, 0.344, 0.270, 0.240] # mlist = [0.981, 1.020, 1.078, 1.117, 1.143, 1.162, 1.196, 1.209] rslist = [1.0,] zlist = [0.662,] mlist = [1.02,] # zlist = [0.786, 0.662, 0.519] # mlist = [0.981, 1.020, 1.078] for (ind, rs) in enumerate(rslist) param = Parameter.rydbergUnit(θ, rs, dim) kF, β = param.kF, param.β Euv, rtol = 1000 * param.EF, 1e-10 # set Nk, minK = 8, 1e-7 for β<1e6; 11, 1e-8 for β<1e7 # Nk, order, minK = 11, 8, 1e-8 Nk, order = 8, 8 maxK, minK = 10kF, 1e-7kF # Euv, rtol = 100 * param.EF, 1e-12 # maxK, minK = 20param.kF, 1e-9param.kF # Nk, order = 16, 6 kgrid = CompositeGrid.LogDensedGrid(:cheb, [0.0, maxK], [0.0, kF], Nk, minK, order) ## test G0 G0 = SelfEnergy.G0wrapped(Euv, rtol, kgrid, param) kF_label = locate(G0.mesh[2], kF) G0_dlr = G0 |> to_dlr G0_tau = G0_dlr |> to_imtime G0_ins = dlr_to_imtime(G0_dlr, [β,]) * (-1) integrand = real(G0_ins[1, :]) .* kgrid.grid density0 = CompositeGrids.Interp.integrate1D(integrand, kgrid) / π @test isapprox(param.n, density0, rtol=3e-5) @time Σ, Σ_ins = SelfEnergy.G0W0(param, Euv, rtol, Nk, maxK, minK, order, :rpa) Z0 = (SelfEnergy.zfactor(param, Σ))[1] z = zlist[ind] @test isapprox(Z0, z, rtol=3e-3) mratio = SelfEnergy.massratio(param, Σ, Σ_ins)[1] m = mlist[ind] @test isapprox(mratio, m, rtol=3e-3) println("θ = $θ, rs= $rs") println("Z-factor = $Z0 ($z), rtol=$(Z0/z-1)") println("m*/m = $mratio ($m), rtol=$(mratio/m-1)") ## test G_RPA G = SelfEnergy.Gwrapped(Σ, Σ_ins, param) G_dlr = G |> to_dlr G_tau = G_dlr |> to_imtime G_ins = dlr_to_imtime(G_dlr, [β,]) * (-1) integrand = real(G_ins[1, :]) .* kgrid.grid density = CompositeGrids.Interp.integrate1D(integrand, kgrid) / π @test isapprox(param.n, density, atol=3e-4) println("density n, from G0, from G_RPA: $(param.n), $density0 (rtol=$(density0/param.n-1)), $density (rtol=$(density/param.n-1))") end end end
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
612
# ElectronGas [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://numericalEFT.github.io/ElectronGas.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://numericalEFT.github.io/ElectronGas.jl/dev) [![Build Status](https://github.com/numericalEFT/ElectronGas.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/numericalEFT/ElectronGas.jl/actions/workflows/CI.yml?query=branch%3Amaster) [![codecov](https://codecov.io/gh/numericalEFT/ElectronGas.jl/branch/master/graph/badge.svg?token=9F4KD8O8W2)](https://codecov.io/gh/numericalEFT/ElectronGas.jl)
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
367
```@meta CurrentModule = ElectronGas ``` # ElectronGas Documentation for [ElectronGas](https://github.com/numericalEFT/ElectronGas.jl). ```@index ``` ## Library Outline ```@contents Pages = [ "lib/parameter.md", "lib/selfenergy.md", "lib/polarization.md", "lib/interaction.md", "lib/legendreinteraction.md", "lib/BSeq.md", ] Depth = 1 ```
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
83
# Bethe-Slapter-type equation solver ```@autodocs Modules = [ElectronGas.BSeq] ```
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
66
# Convention ```@autodocs Modules = [ElectronGas.Convention] ```
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
68
# Interaction ```@autodocs Modules = [ElectronGas.Interaction] ```
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
96
# Legendre Decomposed Interaction ```@autodocs Modules = [ElectronGas.LegendreInteraction] ```
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
64
# Parameter ```@autodocs Modules = [ElectronGas.Parameter] ```
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
70
# Polarization ```@autodocs Modules = [ElectronGas.Polarization] ```
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git
[ "MPL-2.0" ]
0.2.5
3a6ed6c55afc461d479b8ef5114cf6733f2cef56
docs
67
# Self Energy ```@autodocs Modules = [ElectronGas.SelfEnergy] ```
ElectronGas
https://github.com/numericalEFT/ElectronGas.jl.git