forked from kornha/parliament
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfidence.js
More file actions
333 lines (271 loc) · 9.71 KB
/
confidence.js
File metadata and controls
333 lines (271 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
const {logger} = require("firebase-functions");
const {getStatement,
getAllEntitiesForStatement,
updateStatement,
getAllStatementsForEntity,
updateEntity,
getEntity,
getAllStatementsForStory,
updateStory,
getAllStatementsForPost,
updatePost} = require("../common/database");
const {retryAsyncFunction} = require("../common/utils");
// Parameters
const CORRECT_REWARD = 0.05;
const INCORRECT_PENALTY = -0.15;
const DECAY_FACTOR = 0.95; // Exp. decay (1 = slower decay, 0 = faster decay)
const BASE_CONFIDENCE = 0.5;
const DECIDED_THRESHOLD = 0.9;
// ////////////////////////////////////////////////////////////////////////////
// Post
// ////////////////////////////////////////////////////////////////////////////
/**
* E2E Logic onPost for setting confidence
* @param {String} pid
* @return {Promise<void>}
* */
async function onPostShouldChangeConfidence(pid) {
const statements = await getAllStatementsForPost(pid);
const avgConfidence = calculateAverageConfidence(statements);
if (avgConfidence != null) {
logger.info(`Updating Post confidence: ${pid} ${avgConfidence}`);
// skipping error case where post is deleted, since this throws errors
await retryAsyncFunction(() =>
updatePost(pid, {confidence: avgConfidence}, 5));
}
}
// ////////////////////////////////////////////////////////////////////////////
// Story
// ////////////////////////////////////////////////////////////////////////////
/**
* E2E Logic onStory for setting confidence
* @param {String} sid
* @return {Promise<void>}
* */
async function onStoryShouldChangeConfidence(sid) {
const statements = await getAllStatementsForStory(sid);
const avgConfidence = calculateAverageConfidence(statements);
if (avgConfidence != null) {
logger.info(`Updating Story confidence: ${sid} ${avgConfidence}`);
await retryAsyncFunction(() =>
updateStory(sid, {confidence: avgConfidence}));
}
}
// ////////////////////////////////////////////////////////////////////////////
// ENTITY
// ////////////////////////////////////////////////////////////////////////////
/**
* E2E Logic onEntity for setting confidence
* @param {String} eid
* @return {Promise<void>}
*/
async function onEntityShouldChangeConfidence(eid) {
const entity = await getEntity(eid);
if (!entity ||
(entity.adminConfidence != null &&
entity.adminConfidence === entity.confidence)) {
return;
}
// If admin has set confidence, use that always
if (entity.adminConfidence != null) {
logger.info(`Updating Entity confidence: ${eid} ${entity.adminConfidence}`);
await retryAsyncFunction(() =>
updateEntity(eid, {confidence: entity.adminConfidence}));
return;
}
const statements = await getAllStatementsForEntity(eid);
const newConfidence = calculateEntityConfidence(entity, statements);
if (newConfidence != null && entity.confidence !== newConfidence) {
logger.info(`Updating entity confidence: ${eid} ${newConfidence}`);
await retryAsyncFunction(() =>
updateEntity(eid, {confidence: newConfidence}));
}
}
/**
* Calculate the confidence of an entity based on its past statements.
* @param {Entity} entity The entity object.
* @param {Statement[]} statements The array of statement objects.
* @return {number} The confidence of the entity.
*/
function calculateEntityConfidence(entity, statements) {
let totalScore = BASE_CONFIDENCE;
let count = 0;
// Loop through statements most recent first
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (statement.confidence == null) {
continue;
}
count++;
// more recent statements are penalized/rewarded more
const decay = Math.pow(DECAY_FACTOR, i);
const decidedPro = statement.confidence > DECIDED_THRESHOLD;
const decidedAgainst = statement.confidence < 1 - DECIDED_THRESHOLD;
if (!decidedPro && !decidedAgainst) {
continue;
}
let isCorrect = false;
let isIncorrect = false;
if (decidedPro) {
isCorrect = entity.pids.some((pid) => statement.pro.includes(pid));
isIncorrect = entity.pids.some((pid) => statement.against.includes(pid));
} else if (decidedAgainst) {
isCorrect = entity.pids.some((pid) => statement.against.includes(pid));
isIncorrect = entity.pids.some((pid) => statement.pro.includes(pid));
}
// this allows us to weight the confidence equally for distance to 0 or 1
const adjustedConfidence = Math.abs(statement.confidence - 0.5) * 2;
if (isCorrect) {
totalScore +=
CORRECT_REWARD * (1 - totalScore) * decay * adjustedConfidence;
} else if (isIncorrect) {
totalScore +=
INCORRECT_PENALTY * totalScore * decay * adjustedConfidence;
}
}
if (count === 0) {
return null;
}
return Math.max(0, Math.min(1, totalScore));
}
// ////////////////////////////////////////////////////////////////////////////
// STATEMENT
// ////////////////////////////////////////////////////////////////////////////
/**
* E2E Logic onStatement for setting confidence
* @param {String} stid
*/
async function onStatementShouldChangeConfidence(stid) {
const statement = await getStatement(stid);
if (!statement ||
(statement.adminConfidence != null &&
statement.adminConfidence === statement.confidence)) {
return;
}
// If admin has set confidence, use that always
if (statement.adminConfidence != null) {
logger.info(
`Updating statement confidence: ${stid} ${statement.adminConfidence}`);
await retryAsyncFunction(() => updateStatement(stid,
{confidence: statement.adminConfidence}));
return;
}
const entities = await getAllEntitiesForStatement(stid);
const newConfidence = calculateStatementConfidence(statement, entities);
if (newConfidence != null && statement.confidence !== newConfidence) {
logger.info(`Updating statement confidence: ${stid} ${newConfidence}`);
await retryAsyncFunction(() =>
updateStatement(stid, {confidence: newConfidence}));
}
return;
}
/**
* Calculate the confidence of a statement based on its entities.
* @param {Statement} statement The statement id object.
* @param {Entity[]} entities The array of entity objects.
* @return {number} The nullable confidence of the statement.
*/
function calculateStatementConfidence(statement, entities) {
if (entities.length === 0) {
return null;
}
let weightedSum = 0;
let totalWeight = 0;
for (let i = 0; i < entities.length; i++) {
const entity = entities[i];
const pro =
statement.pro?.some((pid) => entity.pids.includes(pid)) ?? false;
const against =
statement.against?.some((pid) => entity.pids.includes(pid)) ?? false;
if (!pro && !against || !entity.confidence) {
continue;
}
let confidence = entity.confidence;
// Reverse confidence if the entity is "anti" the statement
if (against) {
confidence = 1 - confidence;
}
// Inverse Quadratic Weighting: weight = 1 - (1 - confidence)^2
// This is done to weight high/lows confidence more heavily
const weight = 1 - Math.pow(1 - confidence, 2);
// Add to weighted sum
weightedSum += weight * confidence;
totalWeight += weight;
}
// if no entities have confidence, don't update
if (totalWeight == 0) {
return null;
}
// Calculate new confidence
const newConfidence = weightedSum / totalWeight;
// Ensure confidence is within [0, 1]
return Math.max(0, Math.min(1, newConfidence));
}
/**
* Check if a statement crossed the confidence threshold.
* @param {Statement} before The statement object before the change.
* @param {Statement} after The statement object after the change.
* @return {boolean} Whether the statement crossed the threshold.
*/
function confidenceDidCrossThreshold(before, after) {
const negativeThresholdExceeded = (confidence) =>
confidence < 1 - DECIDED_THRESHOLD;
const positiveThresholdExceeded = (confidence) =>
confidence > DECIDED_THRESHOLD;
// If before is null, assume it's starting from BASE_CONFIDENCE
const beforeConfidence = before?.confidence ?? BASE_CONFIDENCE;
const afterConfidence = after?.confidence ?? BASE_CONFIDENCE;
// Check if the threshold has been crossed in either direction
const crossedFromNegativeToPositive =
negativeThresholdExceeded(beforeConfidence) &&
!negativeThresholdExceeded(afterConfidence);
const crossedFromPositiveToNegative =
positiveThresholdExceeded(beforeConfidence) &&
!positiveThresholdExceeded(afterConfidence);
const crossedToNegative =
!negativeThresholdExceeded(beforeConfidence) &&
negativeThresholdExceeded(afterConfidence);
const crossedToPositive =
!positiveThresholdExceeded(beforeConfidence) &&
positiveThresholdExceeded(afterConfidence);
return (
crossedFromNegativeToPositive ||
crossedFromPositiveToNegative ||
crossedToNegative ||
crossedToPositive
);
}
// ////////////////////////////////////////////////////////////////////////////
// Generic
// ////////////////////////////////////////////////////////////////////////////
/**
* Calculate the average confidence of an iterable
* @param {Object[]} iterable The array of objects
* @return {number|null} The average confidence
* */
function calculateAverageConfidence(iterable) {
if (iterable.length === 0) {
return null;
}
let totalConfidence = 0;
let count = 0;
for (const item of iterable) {
if (item.confidence != null) {
totalConfidence += item.confidence;
count++;
}
}
if (count === 0) {
return null;
}
return totalConfidence / count;
}
module.exports = {
confidenceDidCrossThreshold,
onPostShouldChangeConfidence,
onStoryShouldChangeConfidence,
onEntityShouldChangeConfidence,
calculateEntityConfidence,
onStatementShouldChangeConfidence,
calculateStatementConfidence,
};