R/003_utilities_scopes.R

Defines functions .dpp_key with_dpp_scope dpp_scope_active

Documented in dpp_scope_active with_dpp_scope

#####
## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: rsrc_tree/utilities/scopes.R
#####

## CVXPY SOURCE: utilities/scopes.py
## DPP (Disciplined Parameterized Programming) scope management.
##
## When a DPP scope is active, Parameters are treated as affine (not constant).
## This allows curvature analysis to determine if a problem is DPP-compliant,
## which enables caching the solving chain across parameter value changes.

# -- DPP scope state -------------------------------------------------
## Module-level mutable state for DPP scope (reference semantics via environment).
##
## Thread Safety:
## `.dpp_state` is module-level mutable state (single boolean). It is NOT
## thread-safe. Concurrent calls to `with_dpp_scope()` (e.g., via `future`
## with forked workers) would corrupt state. This is acceptable because:
## 1. R is single-threaded by default.
## 2. CVXR does not support parallel backends.
## 3. `withr::local_*` would not help -- the issue is shared state, not cleanup.
## If parallel support is ever added, this would need a per-thread or
## per-session scope mechanism.

.dpp_state <- new.env(parent = emptyenv())
.dpp_state$active <- FALSE

#' Check if DPP Scope is Active
#'
#' @returns Logical; \code{TRUE} if a \code{with_dpp_scope} block is active.
#' @keywords internal
dpp_scope_active <- function() .dpp_state$active

#' Execute Expression Within DPP Scope
#'
#' Within this scope, \code{Parameter} objects are treated as affine
#' (not constant) for curvature analysis. This is used internally by
#' \code{is_dpp()} to check DPP compliance.
#'
#' @param expr An R expression to evaluate within the DPP scope.
#' @returns The result of evaluating \code{expr}.
#' @keywords internal
with_dpp_scope <- function(expr) {
  prev <- .dpp_state$active
  .dpp_state$active <- TRUE
  on.exit(.dpp_state$active <- prev)
  force(expr)
}

# -- DPP-aware cache key helper --------------------------------------
## Returns "key_dpp" when DPP scope is active, "key" otherwise.
## Used by curvature methods to separate normal vs DPP-scope cached results.
## Pre-computed lookup table eliminates paste0() on every call.

.dpp_keys <- list(
  is_constant = "is_constant_dpp",
  is_affine   = "is_affine_dpp",
  is_dcp      = "is_dcp_dpp",
  is_convex   = "is_convex_dpp",
  is_concave  = "is_concave_dpp"
)

.dpp_key <- function(base_key) {
  if (.dpp_state$active) .dpp_keys[[base_key]] else base_key
}

Try the CVXR package in your browser

Any scripts or data that you put into this service are public.

CVXR documentation built on March 6, 2026, 9:10 a.m.