47 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
49 MemoryContext per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
50 MemoryContext oldcontext = MemoryContextSwitchTo(per_query_ctx);
52 TupleDesc tupdesc = rsinfo->expectedDesc;
53 Tuplestorestate *tupstore = tuplestore_begin_heap(
54 rsinfo->allowedModes & SFRM_Materialize_Random,
false, work_mem);
56 rsinfo->returnMode = SFRM_Materialize;
57 rsinfo->setResult = tupstore;
61 const int32 n_signed = PG_GETARG_INT32(1);
65 provsql_error(
"rv_sample: n must be positive (got %d)", n_signed);
66 const unsigned n =
static_cast<unsigned>(n_signed);
68 gate_t root_gate, event_gate;
74 std::optional<gate_t> event_opt;
75 if (gc.getGateType(event_gate) !=
gate_one) event_opt = event_gate;
77 const bool conditional = event_opt.has_value();
79 std::vector<double> samples;
81 const gate_t event = *event_opt;
91 gc, root_gate, event, n);
93 samples = std::move(*direct);
99 const unsigned budget = std::min(
100 static_cast<unsigned>(1000u) * n,
104 gc, root_gate, event, budget);
105 if (cs.accepted.size() > n) cs.accepted.resize(n);
106 if (cs.accepted.size() < n) {
108 (errmsg(
"rv_sample: requested %u, returning %zu "
109 "(acceptance rate %zu/%u)",
110 n, cs.accepted.size(),
111 cs.accepted.size(), cs.attempted)));
113 samples = std::move(cs.accepted);
119 for (
double x : samples) {
120 Datum values[1] = { Float8GetDatum(x) };
121 bool nulls[1] = {
false };
122 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
124 }
catch (
const std::exception &e) {
125 MemoryContextSwitchTo(oldcontext);
128 MemoryContextSwitchTo(oldcontext);
132 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...