31#include "utils/uuid.h"
54void collectStochasticLeaves(
const GenericCircuit &gc,
gate_t g,
55 std::set<gate_t> &out, std::set<gate_t> &seen)
57 if (!seen.insert(g).second)
return;
62 collectStochasticLeaves(gc, c, out, seen);
65std::set<gate_t> stochasticLeaves(
const GenericCircuit &gc,
gate_t g)
67 std::set<gate_t> out, seen;
68 collectStochasticLeaves(gc, g, out, seen);
72bool disjointFrom(
const std::set<gate_t> &a,
const std::set<gate_t> &b)
75 if (b.count(l))
return false;
82struct McDisabledGuard {
103unsigned mc_samples_or_throw(
const std::string &what)
107 throw CircuitException(
108 what +
" could not be decomposed analytically and "
109 "provsql.rv_mc_samples = 0 disables the Monte Carlo fallback");
113 "%s: no closed form found; estimating by Monte Carlo over %d samples "
114 "(an approximation, not an exact moment) -- set provsql.rv_mc_samples = 0 "
115 "to require an exact result instead", what.c_str(), n);
116 return static_cast<unsigned>(n);
122void check_acceptance_or_throw(std::size_t accepted,
unsigned attempted,
123 const std::string &what)
126 throw CircuitException(
127 what +
": conditioning event is infeasible (0 of " +
128 std::to_string(attempted) +
" Monte Carlo samples satisfied it)");
130 unsigned floor = attempted / 1000;
131 if (floor < 5) floor = 5;
132 if (accepted < floor) {
133 throw CircuitException(
134 what +
": conditional MC accepted only " + std::to_string(accepted) +
135 " out of " + std::to_string(attempted) +
136 " samples (need >= " + std::to_string(floor) +
137 "); raise provsql.rv_mc_samples or tighten the event.");
152CovStats mcCovStats(
const GenericCircuit &gc,
gate_t x,
gate_t y,
153 std::optional<gate_t> event,
const std::string &what)
155 const unsigned n = mc_samples_or_throw(what);
157 std::vector<std::optional<double>> xs, ys;
160 check_acceptance_or_throw(cs.xs.size(), cs.attempted, what);
161 xs = std::move(cs.xs);
162 ys = std::move(cs.ys);
167 double sum_x = 0.0, sum_y = 0.0;
171 for (std::size_t i = 0; i < xs.size(); ++i) {
172 if (!xs[i] || !ys[i])
continue;
179 const double mean_x = sum_x /
static_cast<double>(m);
180 const double mean_y = sum_y /
static_cast<double>(m);
182 double cov = 0.0, var_x = 0.0, var_y = 0.0;
183 for (std::size_t i = 0; i < xs.size(); ++i) {
184 if (!xs[i] || !ys[i])
continue;
185 const double dx = *xs[i] - mean_x;
186 const double dy = *ys[i] - mean_y;
191 const double dm =
static_cast<double>(m);
192 return {cov / dm, var_x / dm, var_y / dm};
199std::optional<CovStats> tryAnalyticCovStats(GenericCircuit &gc,
gate_t x,
201 std::optional<gate_t> event,
204 McDisabledGuard guard;
206 CovStats s{0.0, 0.0, 0.0};
209 const gate_t prod = makeProductGate(gc, x, y);
211 s.cov = exy - ex * ey;
217 }
catch (
const CircuitException &) {
235 std::optional<gate_t> event)
250 auto lx = stochasticLeaves(gc, x);
251 auto ly = stochasticLeaves(gc, y);
253 if (event) le = stochasticLeaves(gc, *event);
254 const bool x_indep = disjointFrom(lx, ly) && disjointFrom(lx, le);
255 const bool y_indep = disjointFrom(ly, lx) && disjointFrom(ly, le);
256 if (x_indep || y_indep)
260 if (
auto s = tryAnalyticCovStats(gc, x, y, event,
false))
263 return mcCovStats(gc, x, y, event,
"covariance").cov;
278 std::optional<gate_t> event)
285 if (std::isnan(var) || var <= 0.0)
return std::nullopt;
290 auto lx = stochasticLeaves(gc, x);
291 auto ly = stochasticLeaves(gc, y);
293 if (event) le = stochasticLeaves(gc, *event);
294 const bool x_indep = disjointFrom(lx, ly) && disjointFrom(lx, le);
295 const bool y_indep = disjointFrom(ly, lx) && disjointFrom(ly, le);
296 if (x_indep || y_indep) {
299 if (std::isnan(var_x) || std::isnan(var_y) ||
300 var_x <= 0.0 || var_y <= 0.0)
307 if (
auto exact = tryAnalyticCovStats(gc, x, y, event,
true))
310 s = mcCovStats(gc, x, y, event,
"correlation");
312 if (std::isnan(s.var_x) || std::isnan(s.var_y) ||
313 s.var_x <= 0.0 || s.var_y <= 0.0)
315 return s.cov / std::sqrt(s.var_x * s.var_y);
335 std::vector<gate_t> gates;
339 std::optional<gate_t> event_opt;
341 event_opt = gates[2];
343 return Float8GetDatum(
349 }
catch (
const std::exception &e) {
373 std::vector<gate_t> gates;
376 std::optional<gate_t> event_opt;
378 event_opt = gates[2];
384 return Float8GetDatum(*rho);
389 }
catch (
const std::exception &e) {
GenericCircuit getJointCircuit(const std::vector< pg_uuid_t > &tokens, std::vector< gate_t > &gates)
Multi-root variant of getJointCircuit.
Build in-memory circuits from the mmap-backed persistent store.
gate_t
Strongly-typed gate identifier.
Analytical expectation / variance / moment evaluator over RV circuits.
Monte Carlo sampling over a GenericCircuit, RV-aware.
Datum rv_covariance(PG_FUNCTION_ARGS)
SQL: rv_covariance(x uuid, y uuid, prov uuid) -> float8.
Datum rv_correlation(PG_FUNCTION_ARGS)
SQL: rv_correlation(x uuid, y uuid, prov uuid) -> float8.
std::vector< gate_t > & getWires(gate_t g)
Return a mutable reference to the child-wire list of gate g.
gateType getGateType(gate_t g) const
Return the type of gate g.
void setInfos(gate_t g, unsigned info1, unsigned info2)
Set the integer annotation pair for gate g.
gate_t setGate(gate_type type) override
Allocate a new gate with type type and no UUID.
The quantity asked for has a value in no world (an aggregate over a group empty in every world of pos...
The SIGINT handler installed for the lifetime of the object, the previous one restored as it ends (a ...
gate_t lift_conditioning(GenericCircuit &gc, gate_t root, std::optional< gate_t > &event_opt)
Lift conditioning out of a scalar arithmetic expression.
double computeCovariance(GenericCircuit &gc, gate_t x, gate_t y, std::optional< gate_t > event)
(or ) over a joint circuit.
std::pair< std::vector< std::optional< double > >, std::vector< std::optional< double > > > monteCarloScalarPairSamples(const GenericCircuit &gc, gate_t root_a, gate_t root_b, unsigned samples)
Coupled per-iteration draws of two scalar roots.
std::optional< double > computeCorrelation(GenericCircuit &gc, gate_t x, gate_t y, std::optional< gate_t > event)
Pearson (conditioned on event when set).
double compute_central_moment(const GenericCircuit &gc, gate_t root, unsigned k, std::optional< gate_t > event_root)
Compute the central moment (or if event_root is set).
ConditionalScalarPairSamples monteCarloConditionalScalarPairSamples(const GenericCircuit &gc, gate_t root_a, gate_t root_b, gate_t event_root, unsigned samples)
Rejection-sample the PAIR (root_a, root_b) conditioned on event_root.
double compute_expectation(const GenericCircuit &gc, gate_t root, std::optional< gate_t > event_root)
Compute (or if event_root is set) over the scalar sub-circuit rooted at root.
int provsql_verbose
Verbosity level; controlled by the provsql.verbose_level GUC.
int provsql_rv_mc_samples
Default sample count for analytical-evaluator MC fallbacks; 0 disables fallback (callers raise instea...
Uniform error-reporting macros for ProvSQL.
#define provsql_error(fmt,...)
Report a fatal ProvSQL error and abort the current transaction.
#define provsql_notice(fmt,...)
Emit a ProvSQL informational notice (execution continues).
void provsql_cancel_if_interrupted(void)
Raise PG's cancel if the evaluation stopped for one; nothing otherwise.
Cancellation of the long C++ evaluation loops.
Core types, constants, and utilities shared across ProvSQL.
@ PROVSQL_ARITH_TIMES
n-ary, product of children
@ gate_rv
Continuous random-variable leaf (extra encodes distribution).
@ gate_arith
n-ary arithmetic gate over scalar-valued children (info1 holds operator tag)
C++ utility functions for UUID manipulation.