-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdbStats.js
More file actions
313 lines (268 loc) · 8.48 KB
/
dbStats.js
File metadata and controls
313 lines (268 loc) · 8.48 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
const mongoose = require("mongoose");
const moment = require("moment");
const logger = require("./utils/logger.js");
class MongoStats {
constructor(config = {}) {
this.isConnected = false;
this.uri = config.uri || process.env.MONGO_URI;
this.connectionOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
...config.mongooseOptions,
};
}
// Méthodes de connexion
async connect() {
try {
if (this.isConnected) {
logger.info("Already connected to database");
return;
}
if (!this.uri) {
throw new Error("Database URI is required");
}
await mongoose.connect(this.uri, this.connectionOptions);
this.isConnected = true;
logger.info("Successfully connected to database");
} catch (error) {
logger.error("Connection error:", error);
throw error;
}
}
async disconnect() {
try {
await mongoose.disconnect();
this.isConnected = false;
logger.info("Successfully disconnected from database");
} catch (error) {
logger.error("Disconnection error:", error);
throw error;
}
}
checkConnection() {
if (!this.isConnected) {
throw new Error("Not connected to database");
}
}
// Méthodes statistiques principales
async calculateStatistics(options = {}) {
this.checkConnection();
const { collection, document, period = "month", periodCount = 1 } = options;
try {
let query = {};
let collections = [];
if (collection) {
if (document) {
query = { _id: document };
}
collections = [collection];
} else {
collections = await mongoose.connection.db.listCollections().toArray();
collections = collections.map((col) => col.name);
}
const statistics = {};
for (const collectionName of collections) {
const model =
mongoose.models[collectionName] ||
mongoose.model(
collectionName,
new mongoose.Schema({}, { strict: false })
);
const documents = await model.find(query).lean();
statistics[collectionName] = await this.processCollectionStatistics(
documents,
{ period, periodCount }
);
}
return statistics;
} catch (error) {
logger.error("Error calculating statistics:", error);
throw error;
}
}
async processCollectionStatistics(documents, options) {
const stats = {
totalDocuments: documents.length,
creationDates: [],
documentDetails: [],
modificationCounts: {},
modificationsByPeriod: {},
basicStats: {},
advancedStats: {},
};
// Extraction des données numériques pour les calculs
const numericData = this.extractNumericData(documents);
// Calcul des statistiques de base
stats.basicStats = {
mean: this.calculateMean(numericData),
median: this.calculateMedian(numericData),
mode: this.calculateMode(numericData),
variance: this.calculateVariance(numericData),
standardDeviation: this.calculateStandardDeviation(numericData),
range: this.calculateRange(numericData),
};
// Calcul des statistiques avancées
stats.advancedStats = {
coefficientOfVariation: this.calculateCoefficientOfVariation(numericData),
quartiles: this.calculateQuartiles(numericData),
interquartileRange: this.calculateInterquartileRange(numericData),
skewness: this.calculateSkewness(numericData),
kurtosis: this.calculateKurtosis(numericData),
};
return stats;
}
// Méthodes utilitaires statistiques
calculateMean(arr) {
return arr.length > 0 ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
}
calculateMedian(arr) {
if (arr.length === 0) return 0;
const sorted = [...arr].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2 !== 0
? sorted[middle]
: (sorted[middle - 1] + sorted[middle]) / 2;
}
calculateMode(arr) {
if (arr.length === 0) return 0;
const frequency = {};
let maxFreq = 0;
let mode = arr[0];
arr.forEach((value) => {
frequency[value] = (frequency[value] || 0) + 1;
if (frequency[value] > maxFreq) {
maxFreq = frequency[value];
mode = value;
}
});
return mode;
}
calculateVariance(arr) {
if (arr.length === 0) return 0;
const mean = this.calculateMean(arr);
return this.calculateMean(arr.map((x) => Math.pow(x - mean, 2)));
}
calculateStandardDeviation(arr) {
return Math.sqrt(this.calculateVariance(arr));
}
calculateRange(arr) {
return arr.length > 0 ? Math.max(...arr) - Math.min(...arr) : 0;
}
calculateCoefficientOfVariation(arr) {
const mean = this.calculateMean(arr);
const stdDev = this.calculateStandardDeviation(arr);
return mean !== 0 ? (stdDev / mean) * 100 : 0;
}
calculateQuartiles(arr) {
const sorted = arr.slice().sort((a, b) => a - b);
const Q1 = this.calculateMedian(
sorted.slice(0, Math.floor(sorted.length / 2))
);
const Q2 = this.calculateMedian(sorted);
const Q3 = this.calculateMedian(sorted.slice(Math.ceil(sorted.length / 2)));
return { Q1, Q2, Q3 };
}
calculateInterquartileRange(arr) {
const { Q1, Q3 } = this.calculateQuartiles(arr);
return Q3 - Q1;
}
calculateSkewness(arr) {
const mean = this.calculateMean(arr);
const stdDev = this.calculateStandardDeviation(arr);
const n = arr.length;
if (n < 3 || stdDev === 0) return 0;
return (
(n * arr.reduce((acc, val) => acc + Math.pow(val - mean, 3), 0)) /
((n - 1) * (n - 2) * Math.pow(stdDev, 3))
);
}
calculateKurtosis(arr) {
const mean = this.calculateMean(arr);
const stdDev = this.calculateStandardDeviation(arr);
const n = arr.length;
if (n < 4 || stdDev === 0) return 0;
return (
(n *
(n + 1) *
arr.reduce((acc, val) => acc + Math.pow(val - mean, 4), 0)) /
((n - 1) * (n - 2) * (n - 3) * Math.pow(stdDev, 4)) -
(3 * Math.pow(n - 1, 2)) / ((n - 2) * (n - 3))
);
}
calculateCrossTabulation(arr1, arr2) {
const result = {};
arr1.forEach((val1, index) => {
const val2 = arr2[index];
if (!result[val1]) {
result[val1] = {};
}
result[val1][val2] = (result[val1][val2] || 0) + 1;
});
return result;
}
// Méthodes utilitaires pour le traitement des données
extractNumericData(documents) {
const numericValues = [];
documents.forEach((doc) => {
Object.values(doc).forEach((value) => {
if (typeof value === "number" && !isNaN(value)) {
numericValues.push(value);
}
});
});
return numericValues;
}
// Utilitaires pour les périodes
getPeriodKey(date, period, periodCount) {
const startDate = moment().subtract(periodCount, period);
return `${startDate.format("YYYY-MM-DD")}-${date.format("YYYY-MM-DD")}`;
}
// Méthodes d'analyse croisée
async calculateCrossFieldStatistics(collection, field1, field2) {
this.checkConnection();
try {
const model =
mongoose.models[collection] ||
mongoose.model(collection, new mongoose.Schema({}, { strict: false }));
const documents = await model.find().lean();
const field1Values = documents
.map((doc) => doc[field1])
.filter((v) => v !== undefined);
const field2Values = documents
.map((doc) => doc[field2])
.filter((v) => v !== undefined);
return {
crossTabulation: this.calculateCrossTabulation(
field1Values,
field2Values
),
field1Statistics: {
basic: {
mean: this.calculateMean(field1Values),
median: this.calculateMedian(field1Values),
mode: this.calculateMode(field1Values),
},
advanced: {
skewness: this.calculateSkewness(field1Values),
kurtosis: this.calculateKurtosis(field1Values),
},
},
field2Statistics: {
basic: {
mean: this.calculateMean(field2Values),
median: this.calculateMedian(field2Values),
mode: this.calculateMode(field2Values),
},
advanced: {
skewness: this.calculateSkewness(field2Values),
kurtosis: this.calculateKurtosis(field2Values),
},
},
};
} catch (error) {
logger.error("Error in cross field statistics:", error);
throw error;
}
}
}
module.exports = MongoStats;