46#include "utils/jsonb.h"
47#include "utils/fmgrprotos.h"
48#include "utils/uuid.h"
76void emit_bin(std::ostringstream &out,
bool &first,
77 double lo,
double hi,
double count)
79 if (!first) out <<
',';
81 out <<
"{\"bin_lo\":" << lo
82 <<
",\"bin_hi\":" << hi
83 <<
",\"count\":" << count <<
'}';
92 int bins = PG_GETARG_INT32(1);
96 provsql_error(
"rv_histogram: bins must be positive (got %d)", bins);
98 std::ostringstream out;
102 out << std::setprecision(17);
114 gate_t root_gate, event_gate;
120 Datum json = DirectFunctionCall1(
121 jsonb_in, CStringGetDatum(pstrdup(out.str().c_str())));
122 PG_RETURN_DATUM(json);
126 std::optional<gate_t> event_opt;
132 const bool conditional = event_opt.has_value();
144 emit_bin(out, first, v, v, n);
147 std::vector<double> samples;
157 std::optional<std::vector<std::tuple<double, double, double>>> ahist;
161 for (
const auto &[bl, bh, mass] : *ahist)
162 emit_bin(out, first, bl, bh, mass);
168 (errmsg(
"rv_histogram: no closed-form shape and "
169 "provsql.rv_mc_samples = 0; returning an empty "
182 gc, root_gate, *event_opt, N);
184 samples = std::move(*direct);
187 gc, root_gate, *event_opt, N);
188 if (cs.accepted.empty())
190 "rv_histogram: conditional MC accepted 0 of %u samples; "
191 "raise provsql.rv_mc_samples or check that the event is "
203 samples.erase(std::remove_if(samples.begin(), samples.end(),
204 [](
double x) { return std::isnan(x); }),
206 if (!samples.empty()) {
220 std::sort(samples.begin(), samples.end());
221 const std::size_t n = samples.size();
222 const std::size_t lo_idx = n / 1000;
223 const std::size_t hi_idx = n - 1 - lo_idx;
225 double smin = std::isfinite(support.first)
228 double smax = std::isfinite(support.second)
235 emit_bin(out, first, smin, smax,
236 static_cast<unsigned>(samples.size()));
238 std::vector<unsigned> counts(bins, 0);
239 const double width = (smax - smin) / bins;
240 for (
double x : samples) {
241 int b =
static_cast<int>((x - smin) / width);
243 if (b >= bins) b = bins - 1;
246 for (
int i = 0; i < bins; ++i) {
247 const double lo = smin + i * width;
248 const double hi = (i == bins - 1) ? smax : lo + width;
249 emit_bin(out, first, lo, hi, counts[i]);
257 "rv_histogram: root gate type '%s' is not a scalar "
258 "(expected gate_value, gate_rv, gate_arith, gate_mixture, "
259 "gate_agg, gate_semimod, or gate_case)",
262 }
catch (
const std::exception &e) {
271 Datum json = DirectFunctionCall1(
272 jsonb_in, CStringGetDatum(pstrdup(out.str().c_str())));
273 PG_RETURN_DATUM(json);
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.
Semiring-agnostic in-memory provenance circuit.
Monte Carlo sampling over a GenericCircuit, RV-aware.
Continuous random-variable helpers (distribution parsing, moments).
Support-based bound check for continuous-RV comparators.
Datum rv_histogram(PG_FUNCTION_ARGS)
Exception type thrown by circuit operations on invalid input.
gateType getGateType(gate_t g) const
Return the type of gate g.
std::string getExtra(gate_t g) const
Return the string extra for gate g.
The SIGINT handler installed for the lifetime of the object, the previous one restored as it ends (a ...
std::pair< double, double > compute_support(const GenericCircuit &gc, gate_t root, std::optional< gate_t > event_root)
Compute the [lo, hi] support interval of a scalar sub-circuit rooted at root.
std::optional< ClosedFormShape > matchClosedFormDistribution(const GenericCircuit &gc, gate_t root, std::optional< gate_t > event_root)
Detect any of the closed-form shapes supported by rv_analytical_curves.
std::vector< std::optional< double > > monteCarloScalarSamples(const GenericCircuit &gc, gate_t root, unsigned samples)
Sample a scalar sub-circuit samples times and return the draws.
gate_t lift_conditioning(GenericCircuit &gc, gate_t root, std::optional< gate_t > &event_opt)
Lift conditioning out of a scalar arithmetic expression.
std::optional< std::vector< std::tuple< double, double, double > > > analyticalHistogram(const ClosedFormShape &shape, int bins)
Exact histogram (bin_lo, bin_hi, probability mass) of a closed-form shape, in bins equal-width bins o...
double parseDoubleStrict(const std::string &s)
Strictly parse s as a double.
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...
std::vector< double > definedDraws(const std::vector< std::optional< double > > &samples)
The draws of samples that have a value, in order.
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.
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.
const char * gate_type_name[]
Names of gate types.
Core types, constants, and utilities shared across ProvSQL.
@ gate_rv
Continuous random-variable leaf (extra encodes distribution).
@ gate_case
N-ary guarded selection over scalar (RV) children: wires are [guard_1, value_1, .....
@ gate_mixture
Probabilistic mixture: three wires [p_token (gate_input Bernoulli), x_token, y_token]; samples x when...
@ gate_arith
n-ary arithmetic gate over scalar-valued children (info1 holds operator tag)
C++ utility functions for UUID manipulation.