ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
shapley.cpp
Go to the documentation of this file.
1/**
2 * @file shapley.cpp
3 * @brief SQL functions for Shapley and Banzhaf power-index computation.
4 *
5 * Implements two SQL-callable functions:
6 * - @c provsql.shapley(token, variable, method, args): Shapley value of
7 * a given input gate (tuple) in the provenance circuit rooted at @p token.
8 * - @c provsql.shapley_all_vars(token, method, args): Shapley values for
9 * all input gates simultaneously (more efficient than calling @c shapley()
10 * once per variable).
11 *
12 * The @p method argument selects the d-DNNF construction:
13 * - empty / @c "default" / @c "auto": cost-select the cheapest route via the
14 * probability catalog's chooser.
15 * - @c "tree-decomposition": exact, polynomial if treewidth ≤ @c MAX_TREEWIDTH.
16 * - @c "interpret-as-dd": direct interpretation of the circuit as a d-DNNF.
17 * - @c "compilation": external knowledge compiler, named in @p args
18 * (@c "d4", @c "c2d", …); empty @p args picks the highest-preference one.
19 *
20 * Banzhaf power index computation is exposed via the same internal helper
21 * (@c shapley_internal with @c banzhaf=true), called by the
22 * @c provsql.banzhaf() SQL function defined in the SQL layer.
23 */
24extern "C" {
25#include "postgres.h"
26#include "fmgr.h"
27#include "catalog/pg_type.h"
28#include "utils/uuid.h"
29#include "executor/spi.h"
30#include "provsql_shmem.h"
31#include "provsql_utils.h"
32
33PG_FUNCTION_INFO_V1(shapley);
34PG_FUNCTION_INFO_V1(shapley_all_vars);
35}
36
37#include "c_cpp_compatibility.h"
38#include "BooleanCircuit.h"
39#include "ProbabilityMethod.h"
40#include "GenericCircuit.h"
41#include "Circuit.hpp"
42#include <unordered_map>
43#include "provsql_utils_cpp.h"
45#include "CircuitFromMMap.h"
46#include "tool_registry_sync.h"
47#include <fstream>
48
49using namespace std;
50
51/**
52 * @brief Core implementation for Shapley and Banzhaf index computation.
53 * @param token UUID of the root provenance gate.
54 * @param variable UUID of the input gate whose index is to be computed.
55 * @param method d-DNNF compilation method.
56 * @param args Additional arguments for the compilation method.
57 * @param banzhaf If @c true, compute the Banzhaf index instead of Shapley.
58 * @return The Shapley (or Banzhaf) value of @p variable.
59 */
60static double shapley_internal
61 (pg_uuid_t token, pg_uuid_t variable, const std::string &method, const std::string &args, bool banzhaf)
62{
63 /* A conditioned token (X | C) is refused: Shapley / Banzhaf are linear in
64 * their value function, whereas P(X|C) = P(X∧C)/P(C) is a non-linear ratio,
65 * so the conditional indices are not a combination of the unconditioned
66 * ones and have no implementation here. Detect the conditioned root and
67 * raise a Shapley-specific message rather than the generic semiring-refusal
68 * thrown deeper in the Boolean-circuit build. */
71 provsql_error("shapley/banzhaf: conditional Shapley / Banzhaf values are "
72 "not supported -- a conditioned token (X | C) cannot be "
73 "passed to shapley() / banzhaf(). Compute the index on the "
74 "unconditioned token, or use probability_evaluate for the "
75 "conditional probability P(X|C)");
76 gate_t root;
77 std::unordered_map<gate_t, gate_t> gc_to_bc;
78 BooleanCircuit c = getBooleanCircuit(gc, token, root, gc_to_bc);
79
81 provsql_error("Computing Shapley/Banzhaf values is ill-defined for circuits with multivalued (mulinput) gates");
82
83 if(c.getGateType(c.getGate(uuid2string(variable))) != BooleanGate::IN)
84 return 0.;
85
86 // Default / "auto": cost-select the d-D construction (interpret-as-dd /
87 // tree-decomposition / compilation) via the probability catalog's chooser;
88 // any other method (tree-decomposition / interpret-as-dd / compilation, the
89 // latter with a compiler name in `args`) is taken by name.
90 dDNNF dd = (method.empty() || method == "default" || method == "auto")
91 ? provsql::makeDDAuto(c, root)
92 : c.makeDD(root, method, args);
93
94 dd.makeSmooth();
95 if(!banzhaf)
97
98 auto var_gate=dd.getGate(uuid2string(variable));
99
100 double result;
101
102 if(!banzhaf)
103 result = dd.shapley(var_gate);
104 else
105 result = dd.banzhaf(var_gate);
106
107 return result;
108}
109
110/** @brief PostgreSQL-callable wrapper for shapley() and banzhaf(). */
111Datum shapley(PG_FUNCTION_ARGS)
112{
113 provsql_sync_tool_registry(); // honour persisted tool-registry overrides
114 try {
115 if(PG_ARGISNULL(0) || PG_ARGISNULL(1))
116 PG_RETURN_NULL();
117
118 Datum token = PG_GETARG_DATUM(0);
119 Datum variable = PG_GETARG_DATUM(1);
120
121 std::string method;
122 if(!PG_ARGISNULL(2)) {
123 text *t = PG_GETARG_TEXT_P(2);
124 method = string(VARDATA(t),VARSIZE(t)-VARHDRSZ);
125 }
126
127 std::string args;
128 if(!PG_ARGISNULL(3)) {
129 text *t = PG_GETARG_TEXT_P(3);
130 args = string(VARDATA(t),VARSIZE(t)-VARHDRSZ);
131 }
132
133 bool banzhaf = false;
134 if(!PG_ARGISNULL(4)) {
135 banzhaf = PG_GETARG_BOOL(4);
136 }
137
138 PG_RETURN_FLOAT8(shapley_internal(*DatumGetUUIDP(token), *DatumGetUUIDP(variable), method, args, banzhaf));
139 } catch(const std::exception &e) {
140 provsql_error("shapley: %s", e.what());
141 } catch(...) {
142 provsql_error("shapley: Unknown exception");
143 }
144
145 PG_RETURN_NULL();
146}
147
148/** @brief PostgreSQL-callable wrapper for shapley_all_vars() set-returning function. */
149Datum shapley_all_vars(PG_FUNCTION_ARGS)
150{
151 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
152
153 MemoryContext per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
154 MemoryContext oldcontext = MemoryContextSwitchTo(per_query_ctx);
155
156 TupleDesc tupdesc = rsinfo->expectedDesc;
157 Tuplestorestate *tupstore = tuplestore_begin_heap(rsinfo->allowedModes & SFRM_Materialize_Random, false, work_mem);
158
159 rsinfo->returnMode = SFRM_Materialize;
160 rsinfo->setResult = tupstore;
161
162 if(!PG_ARGISNULL(0)) {
163 pg_uuid_t token = *DatumGetUUIDP(PG_GETARG_DATUM(0));
164
165 std::string method;
166 if(!PG_ARGISNULL(1)) {
167 text *t = PG_GETARG_TEXT_P(1);
168 method = string(VARDATA(t),VARSIZE(t)-VARHDRSZ);
169 }
170
171 std::string args;
172 if(!PG_ARGISNULL(2)) {
173 text *t = PG_GETARG_TEXT_P(2);
174 args = string(VARDATA(t),VARSIZE(t)-VARHDRSZ);
175 }
176
177 bool banzhaf = false;
178 if(!PG_ARGISNULL(3)) {
179 banzhaf = PG_GETARG_BOOL(3);
180 }
181
182
184 if(gc.getGateType(gc.getGate(uuid2string(token))) == gate_conditioned)
185 provsql_error("shapley/banzhaf: conditional Shapley / Banzhaf values are "
186 "not supported -- a conditioned token (X | C) cannot be "
187 "passed to shapley() / banzhaf(). Compute the index on the "
188 "unconditioned token, or use probability_evaluate for the "
189 "conditional probability P(X|C)");
190 gate_t root;
191 std::unordered_map<gate_t, gate_t> gc_to_bc;
192 BooleanCircuit c = getBooleanCircuit(gc, token, root, gc_to_bc);
193
194 if(c.hasMultivaluedGates())
195 provsql_error("Computing Shapley/Banzhaf values is ill-defined for circuits with multivalued (mulinput) gates");
196
197 dDNNF dd = (method.empty() || method == "default" || method == "auto")
198 ? provsql::makeDDAuto(c, root)
199 : c.makeDD(root, method, args);
200 dd.makeSmooth();
201 if(!banzhaf)
203
204 for(auto &v_circuit_gate: c.getInputs()) {
205 auto var_uuid_string = c.getUUID(v_circuit_gate);
206 auto var_gate=dd.getGate(var_uuid_string);
207 pg_uuid_t *uuidp = reinterpret_cast<pg_uuid_t*>(palloc(UUID_LEN));
208 *uuidp = string2uuid(var_uuid_string);
209
210 double result;
211
212 if(!banzhaf)
213 result = dd.shapley(var_gate);
214 else
215 result = dd.banzhaf(var_gate);
216
217 Datum values[2] = {
218 UUIDPGetDatum(uuidp), Float8GetDatum(result)
219 };
220 bool nulls[sizeof(values)] = {0, 0};
221
222 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
223 }
224 }
225
226 MemoryContextSwitchTo(oldcontext);
227
228 PG_RETURN_NULL();
229}
Boolean provenance circuit with support for knowledge compilation.
@ AND
Logical conjunction of child gates.
@ IN
Input (variable) gate representing a base tuple.
BooleanCircuit getBooleanCircuit(GenericCircuit &gc, pg_uuid_t token, gate_t &gate, std::unordered_map< gate_t, gate_t > &gc_to_bc)
Build a BooleanCircuit from an already-loaded GenericCircuit.
GenericCircuit getGenericCircuit(pg_uuid_t token)
Build a GenericCircuit from the mmap store rooted at token.
Build in-memory circuits from the mmap-backed persistent store.
gate_t
Strongly-typed gate identifier.
Definition Circuit.h:49
Out-of-line template method implementations for Circuit<gateType>.
Semiring-agnostic in-memory provenance circuit.
Catalog of probability-evaluation methods (Strategy + registry).
Fix macro conflicts between PostgreSQL headers and the C++ STL/Boost.
Boolean circuit for provenance formula evaluation.
const std::set< gate_t > & getInputs() const
Return the set of input (IN) gate IDs.
dDNNF makeDD(gate_t g, const std::string &method, const std::string &args) const
Dispatch to the appropriate d-DNNF construction method.
bool hasMultivaluedGates() const
Return true if the circuit contains any MULIN gates.
gateType getGateType(gate_t g) const
Return the type of gate g.
Definition Circuit.h:130
uuid getUUID(gate_t g) const
Return the UUID string associated with gate g.
Definition Circuit.hpp:46
gate_t getGate(const uuid &u)
Return (or create) the gate associated with UUID u.
Definition Circuit.hpp:33
In-memory provenance circuit with semiring-generic evaluation.
A d-DNNF circuit supporting exact probabilistic and game-theoretic evaluation.
Definition dDNNF.h:71
void makeSmooth()
Make the d-DNNF smooth.
Definition dDNNF.cpp:61
void makeGatesBinary(BooleanGate type)
Rewrite all n-ary AND/OR gates into binary trees.
Definition dDNNF.cpp:108
double shapley(gate_t var) const
Compute the Shapley value of input gate var.
Definition dDNNF.cpp:526
double banzhaf(gate_t var) const
Compute the Banzhaf power index of input gate var.
Definition dDNNF.cpp:554
Constructs a d-DNNF from a Boolean circuit and its tree decomposition.
dDNNF makeDDAuto(BooleanCircuit &c, gate_t g)
Cost-select a d-DNNF construction route for gate g of Boolean circuit c and build it – the default ma...
#define provsql_error(fmt,...)
Report a fatal ProvSQL error and abort the current transaction.
Shared-memory segment and inter-process pipe management.
Core types, constants, and utilities shared across ProvSQL.
@ gate_conditioned
Conditioning marker with two children [target, evidence]: measure-only, probability_evaluate returns ...
#define UUID_LEN
Number of bytes in a UUID.
pg_uuid_t string2uuid(const string &source)
Parse a UUID string into a pg_uuid_t.
string uuid2string(pg_uuid_t uuid)
Format a pg_uuid_t as a std::string.
C++ utility functions for UUID manipulation.
static double shapley_internal(pg_uuid_t token, pg_uuid_t variable, const std::string &method, const std::string &args, bool banzhaf)
Core implementation for Shapley and Banzhaf index computation.
Definition shapley.cpp:61
Datum shapley(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for shapley() and banzhaf().
Definition shapley.cpp:111
Datum shapley_all_vars(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for shapley_all_vars() set-returning function.
Definition shapley.cpp:149
UUID structure.
void provsql_sync_tool_registry()
Rebuild the in-memory registry as "compiled seed overlaid with the provsql.tool_overrides rows"...
Reload the in-memory external-tool registry from its persistent overrides.