Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCarbonIntensity.php
More file actions
373 lines (334 loc) · 12.8 KB
/
Copy pathCarbonIntensity.php
File metadata and controls
373 lines (334 loc) · 12.8 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
<?php
/**
* -------------------------------------------------------------------------
* Carbon plugin for GLPI
*
* @copyright Copyright (C) 2024-2025 Teclib' and contributors.
* @license https://www.gnu.org/licenses/gpl-3.0.txt GPLv3+
* @link https://github.com/pluginsGLPI/carbon
*
* -------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of Carbon plugin for GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/
namespace GlpiPlugin\Carbon;
use CommonDropdown;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use DBmysql;
use Exception;
use Glpi\DBAL\QueryParam;
use GlpiPlugin\Carbon\DataSource\CarbonIntensity\ClientInterface;
use Override;
use Symfony\Component\Console\Helper\ProgressBar;
/**
* Some data sources
*
* Carbon intensity of electricity productiion for many countries, yearly
*including a value for the whole world
* https://ourworldindata.org/grapher/carbon-intensity-electricity?tab=chart
*/
/**
* Undocumented class
*/
class CarbonIntensity extends CommonDropdown
{
private const MIN_HISTORY_LENGTH = '13 months ago';
public static $rightname = 'carbon:report';
#[Override]
public static function getTypeName($nb = 0)
{
return __("Carbon intensity", 'carbon');
}
#[Override]
public static function getIcon(): string
{
return 'fa-solid fa-solar-panel';
}
#[Override]
public function rawSearchOptions()
{
$tab = parent::rawSearchOptions();
// Name is useless; do not show it. The column is required to avoid SQL errors, all dropdown must have a name column
// $tab[1]['datatype'] = 'text'; // To show 'name' column but make it not clickable
unset($tab[1]);
$table = self::getTable();
$tab[] = [
'id' => '3',
'table' => $table,
'field' => 'date',
'name' => __('Emission date', 'carbon'),
'massiveaction' => false, // implicit field is id
'datatype' => 'datetime',
];
$tab[] = [
'id' => SearchOptions::CARBON_INTENSITY_SOURCE,
'table' => Source::getTable(),
'field' => 'name',
'name' => Source::getTypeName(1),
'massiveaction' => false, // implicit field is id
'datatype' => 'dropdown',
];
$tab[] = [
'id' => SearchOptions::CARBON_INTENSITY_ZONE,
'table' => Zone::getTable(),
'field' => 'name',
'name' => Zone::getTypeName(1),
'massiveaction' => false, // implicit field is id
'datatype' => 'dropdown',
];
$tab[] = [
'id' => SearchOptions::CARBON_INTENSITY_INTENSITY,
'table' => $table,
'field' => 'intensity',
'name' => __('Intensity', 'carbon'),
'massiveaction' => false, // implicit field is id
'datatype' => 'decimal',
'unit' => 'gCO₂eq/KWh',
];
return $tab;
}
/**
* get carbon intensity dates for a source and a zone
*
* @param Source_Zone $source_zone Source_Zone to examinate
* @return array
*/
private function getKnownDatesQuery(Source_Zone $source_zone)
{
$intensity_table = CarbonIntensity::getTable();
$source_table = Source::getTable();
$zone_table = Zone::getTable();
$source_fk = getForeignKeyFieldForItemType(Source::class);
$zone_fk = getForeignKeyFieldForItemType(Zone::class);
return [
'SELECT' => [$intensity_table => ['id', 'date']],
'FROM' => $intensity_table,
'INNER JOIN' => [
$source_table => [
'FKEY' => [
$intensity_table => Source::getForeignKeyField(),
$source_table => 'id',
],
],
$zone_table => [
'FKEY' => [
$intensity_table => Zone::getForeignKeyField(),
$zone_table => 'id',
],
],
],
'WHERE' => [
$source_fk => $source_zone->fields[$source_fk],
$zone_fk => $source_zone->fields[$zone_fk],
],
];
}
/**
* Get the last known date of carbon emissiosn
*
* @param Source_Zone $source_zone Source_Zone to examinate
* @return DateTimeImmutable
*/
public function getLastKnownDate(Source_Zone $source_zone): ?DateTimeImmutable
{
/** @var DBmysql $DB */
global $DB;
$request = $this->getKnownDatesQuery($source_zone);
$request['ORDER'] = CarbonIntensity::getTableField('date') . ' DESC';
$request['LIMIT'] = '1';
$result = $DB->request($request)->current();
if ($result === null) {
return null;
}
return DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $result['date']);
}
/**
* Get the first known date of carbon emissiosn
*
* @param Source_Zone $source_zone
* @return DateTimeImmutable
*/
public function getFirstKnownDate(Source_Zone $source_zone): ?DateTimeImmutable
{
/** @var DBmysql $DB */
global $DB;
$request = $this->getKnownDatesQuery($source_zone);
$request['ORDER'] = CarbonIntensity::getTableField('date') . ' ASC';
$request['LIMIT'] = '1';
$result = $DB->request($request)->current();
if ($result === null) {
return null;
}
return DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $result['date']);
}
/**
* Download data for a single zone
*
* @param ClientInterface $data_source
* @param Source_Zone $source_zone
* @param int $limit maximum count of items to process
* @param ProgressBar $progress_bar progress bar to update (CLI mode only)
* @return int count of item downloaded
*/
public function downloadOneZone(ClientInterface $data_source, Source_Zone $source_zone, int $limit = 0, ?ProgressBar $progress_bar = null): int
{
$start_date = max($this->getDownloadStartDate(), $data_source->getHardStartDate());
$total_count = 0;
// Check if there are gaps to fill
$gaps = $this->findGaps($source_zone, $start_date);
if (count($gaps) === 0) {
// Log a notice specifying the source and the zone
$zone = new Zone();
$zone->getFromDBByCrit(['id' => $source_zone->fields[Zone::getForeignKeyField()]]);
trigger_error(sprintf(
"No gap to fill for source %s and zone %s between %s and %s",
$data_source->getSourceName(),
$zone->fields['name'],
$start_date->format('Y-m-d'),
'now'
), E_USER_WARNING);
}
if ($progress_bar) {
$hours_to_download = 0;
// Count the total days to download
foreach ($gaps as $gap) {
$gap_start = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $gap['start']);
$gap_end = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $gap['end']);
$diff = $gap_start->diff($gap_end);
$hours_to_download += $diff->days * 24 + $diff->h;
}
$progress_bar->setMaxSteps($hours_to_download);
}
foreach ($gaps as $gap) {
$gap_start = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $gap['start']);
$gap_end = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $gap['end']);
$count = $data_source->fullDownload($source_zone, $gap_start, $gap_end, $this, $limit, $progress_bar);
$total_count += $count;
if ($total_count >= $limit) {
return $total_count;
}
}
return $total_count;
}
/**
* Get the oldest date where data are required
*
* @return DateTimeImmutable|null
*/
public function getDownloadStartDate(): ?DateTimeImmutable
{
// Get the default oldest date od data to download
$start_date = new DateTime(self::MIN_HISTORY_LENGTH);
$start_date->setTime(0, 0, 0);
$start_date = DateTimeImmutable::createFromMutable($start_date);
// Get the oldest date between the oldest asset in the inventory and the previous one
$toolbox = new Toolbox();
$oldest_asset_date = $toolbox->getOldestAssetDate();
if ($oldest_asset_date !== null) {
$start_date = min($start_date, $oldest_asset_date);
}
return $start_date;
}
// /**
// * Get date where data download shall end, excluding the incremental download mode for the specified data source
// *
// * @param string $zone_name zone to examine
// * @param ClientInterface $data_source data source
// * @return DateTimeImmutable
// */
// public function getDownloadStopDate(string $zone_name, ClientInterface $data_source): DateTimeImmutable
// {
// $stop_date = $data_source->getMaxIncrementalAge();
// $first_known_intensity_date = $this->getFirstKnownDate($zone_name, $data_source->getSourceName());
// if ($first_known_intensity_date !== null) {
// $first_known_intensity_date = $first_known_intensity_date->sub(new DateInterval('PT1H'));
// $stop_date = min($stop_date, $first_known_intensity_date);
// }
// return $stop_date;
// }
/**
* Save in database the carbon intensities
* Give up on failures
*
* @param Source_Zone $source_zone Source_zone
* @param array $data as an array of arrays ['datetime' => string, 'intensity' => float]
* @return int count of actually saved items,
*/
public function save(Source_Zone $source_zone, array $data): int
{
/** @var DBmysql $DB */
global $DB;
$count = 0;
$source_fk = getForeignKeyFieldForItemType(Source::class);
$zone_fk = getForeignKeyFieldForItemType(Zone::class);
$query = $DB->buildInsert(
CarbonIntensity::getTable(),
[
'date' => new QueryParam(),
$source_fk => new QueryParam(),
$zone_fk => new QueryParam(),
'intensity' => new QueryParam(),
'data_quality' => new QueryParam(),
],
);
$stmt = $DB->prepare($query);
foreach ($data as $intensity) {
try {
$stmt->bind_param(
'siidi',
$intensity['datetime'],
$source_zone->fields[$source_fk],
$source_zone->fields[$zone_fk],
$intensity['intensity'],
$intensity['data_quality']
);
$DB->executeStatement($stmt);
$count++;
} catch (Exception $e) {
$count++;
continue;
}
}
$stmt->close();
return $count;
}
/**
* Gets date intervals where data are missing
*
* @param Source_Zone $source_zone
* @param DateTimeInterface $start
* @param DateTimeInterface|null $stop
* @return array
*/
public function findGaps(Source_Zone $source_zone, DateTimeInterface $start, ?DateTimeInterface $stop = null): array
{
$source_fk = getForeignKeyFieldForItemType(Source::class);
$zone_fk = getForeignKeyFieldForItemType(Zone::class);
$criteria = [
$source_fk => $source_zone->fields[$source_fk],
$zone_fk => $source_zone->fields[$zone_fk],
];
$interval = new DateInterval('PT1H');
return Toolbox::findTemporalGapsInTable(self::getTable(), $start, $interval, $stop, $criteria);
}
}
You can’t perform that action at this time.
