45 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
47 MemoryContext per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
48 MemoryContext oldcontext = MemoryContextSwitchTo(per_query_ctx);
50 TupleDesc tupdesc = rsinfo->expectedDesc;
51 Tuplestorestate *tupstore = tuplestore_begin_heap(
52 rsinfo->allowedModes & SFRM_Materialize_Random,
false, work_mem);
54 rsinfo->returnMode = SFRM_Materialize;
55 rsinfo->setResult = tupstore;
59 const int32 n_signed = PG_GETARG_INT32(1);
63 provsql_error(
"rv_sample: n must be positive (got %d)", n_signed);
64 const unsigned n =
static_cast<unsigned>(n_signed);
66 gate_t root_gate, event_gate;
69 const bool conditional = gc.getGateType(event_gate) !=
gate_one;
71 std::vector<double> samples;
82 gc, root_gate, event_gate, n);
84 samples = std::move(*direct);
90 const unsigned budget = std::min(
91 static_cast<unsigned>(1000u) * n,
95 gc, root_gate, event_gate, budget);
96 if (cs.accepted.size() > n) cs.accepted.resize(n);
97 if (cs.accepted.size() < n) {
99 (errmsg(
"rv_sample: requested %u, returning %zu "
100 "(acceptance rate %zu/%u)",
101 n, cs.accepted.size(),
102 cs.accepted.size(), cs.attempted)));
104 samples = std::move(cs.accepted);
110 for (
double x : samples) {
111 Datum values[1] = { Float8GetDatum(x) };
112 bool nulls[1] = {
false };
113 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
115 }
catch (
const std::exception &e) {
116 MemoryContextSwitchTo(oldcontext);
119 MemoryContextSwitchTo(oldcontext);
123 MemoryContextSwitchTo(oldcontext);
GenericCircuit getJointCircuit(pg_uuid_t root_token, pg_uuid_t event_token, gate_t &root_gate, gate_t &event_gate)
Build a GenericCircuit containing the closures of two roots, with shared subgraphs unified.
ConditionalScalarSamples monteCarloConditionalScalarSamples(const GenericCircuit &gc, gate_t root, gate_t event_root, unsigned samples)
Rejection-sample root conditioned on event_root.
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...