26#include "utils/builtins.h"
27#include "utils/tuplestore.h"
28#include "utils/uuid.h"
50 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
52 MemoryContext per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
53 MemoryContext oldcontext = MemoryContextSwitchTo(per_query_ctx);
55 TupleDesc tupdesc = rsinfo->expectedDesc;
56 Tuplestorestate *tupstore = tuplestore_begin_heap(
57 rsinfo->allowedModes & SFRM_Materialize_Random,
false, work_mem);
59 rsinfo->returnMode = SFRM_Materialize;
60 rsinfo->setResult = tupstore;
64 const int32 n_signed = PG_GETARG_INT32(1);
68 provsql_error(
"rv_sample: n must be positive (got %d)", n_signed);
69 const unsigned n =
static_cast<unsigned>(n_signed);
71 gate_t root_gate, event_gate;
77 std::optional<gate_t> event_opt;
78 if (gc.getGateType(event_gate) !=
gate_one) event_opt = event_gate;
80 const bool conditional = event_opt.has_value();
82 std::vector<double> samples;
84 const gate_t event = *event_opt;
93 for (
unsigned i = 0; i < n; ++i)
94 samples.push_back(dist->sample(rng));
101 const unsigned budget =
106 if (post.particles.empty() || post.weight_sum <= 0.0)
108 "rv_sample: evidence is infeasible (no positive-weight draw "
109 "among %u Monte Carlo samples); the observations may contradict "
110 "the prior, or raise provsql.rv_mc_samples", budget);
122 gc, root_gate, event, n);
124 samples = std::move(*direct);
130 const unsigned budget = std::min(
131 static_cast<unsigned>(1000u) * n,
135 gc, root_gate, event, budget);
136 if (cs.accepted.size() > n) cs.accepted.resize(n);
137 if (cs.accepted.size() < n) {
139 (errmsg(
"rv_sample: requested %u, returning %zu "
140 "(acceptance rate %zu/%u)",
141 n, cs.accepted.size(),
142 cs.accepted.size(), cs.attempted)));
144 samples = std::move(cs.accepted);
151 for (
double x : samples) {
152 Datum values[1] = { Float8GetDatum(x) };
153 bool nulls[1] = {
false };
154 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
156 }
catch (
const std::exception &e) {
157 MemoryContextSwitchTo(oldcontext);
160 MemoryContextSwitchTo(oldcontext);
164 MemoryContextSwitchTo(oldcontext);
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.
Exact conjugate-prior posteriors for observe-evidence circuits.
Per-family polymorphic view over a continuous gate_rv distribution (§F.1 class hierarchy).
Analytical expectation / variance / moment evaluator over RV circuits.
Semiring-agnostic in-memory provenance circuit.
Monte Carlo sampling over a GenericCircuit, RV-aware.
Datum rv_sample(PG_FUNCTION_ARGS)
gate_t lift_conditioning(GenericCircuit &gc, gate_t root, std::optional< gate_t > &event_opt)
Lift conditioning out of a scalar arithmetic expression.
std::vector< double > posteriorResample(const WeightedPosterior &post, unsigned n)
Sampling-importance-resampling: draw n posterior samples from a weighted particle set (proportional t...
std::unique_ptr< Distribution > makeDistribution(const DistributionSpec &spec)
Construct the per-family Distribution for a parsed spec.
std::mt19937_64 seedRng()
The shared Monte Carlo generator, seeded from the provsql.monte_carlo_seed GUC (-1 = non-deterministi...
ConditionalScalarSamples monteCarloConditionalScalarSamples(const GenericCircuit &gc, gate_t root, gate_t event_root, unsigned samples)
Rejection-sample root conditioned on event_root.
std::optional< DistributionSpec > conjugatePosterior(const GenericCircuit &gc, gate_t target, gate_t evidence)
The exact posterior of target given evidence, as a resolved distribution spec, when the circuit match...
std::vector< double > monteCarloScalarSamples(const GenericCircuit &gc, gate_t root, unsigned samples)
Sample a scalar sub-circuit samples times and return the draws.
std::optional< std::vector< double > > try_truncated_closed_form_sample(const GenericCircuit &gc, gate_t root, gate_t event_root, unsigned n)
Try to draw n exact samples from the conditional distribution of root given event_root via closed-for...
WeightedPosterior importanceSampleConditional(const GenericCircuit &gc, gate_t root, gate_t evidence, unsigned samples)
Self-normalised importance sampling of root given evidence.
bool circuitHasObserve(const GenericCircuit &gc, gate_t root)
Whether the circuit reachable from root contains a gate_observe – the signal that a conditioning even...
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.
Core types, constants, and utilities shared across ProvSQL.
C++ utility functions for UUID manipulation.