Passed
Push — master ( dc4cf6...d9c3b0 )
by Guangyu
02:47 queued 10s
created

reports.tenantstatistics   F

Complexity

Total Complexity 109

Size/Duplication

Total Lines 613
Duplicated Lines 98.37 %

Importance

Changes 0
Metric Value
eloc 467
dl 603
loc 613
rs 2
c 0
b 0
f 0
wmc 109

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Reporting.on_options() 3 3 1
A Reporting.__init__() 3 3 1
F Reporting.on_get() 581 581 107

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like reports.tenantstatistics often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
import utilities
7
from decimal import *
8
9
10 View Code Duplication
class Reporting:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
11
    @staticmethod
12
    def __init__():
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    ####################################################################################################################
20
    # PROCEDURES
21
    # Step 1: valid parameters
22
    # Step 2: query the tenant
23
    # Step 3: query energy categories
24
    # Step 4: query associated sensors
25
    # Step 5: query associated points
26
    # Step 6: query base period energy input
27
    # Step 7: query reporting period energy input
28
    # Step 8: query tariff data
29
    # Step 9: query associated sensors and points data
30
    # Step 10: construct the report
31
    ####################################################################################################################
32
    @staticmethod
33
    def on_get(req, resp):
34
        print(req.params)
35
        tenant_id = req.params.get('tenantid')
36
        period_type = req.params.get('periodtype')
37
        base_start_datetime_local = req.params.get('baseperiodstartdatetime')
38
        base_end_datetime_local = req.params.get('baseperiodenddatetime')
39
        reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime')
40
        reporting_end_datetime_local = req.params.get('reportingperiodenddatetime')
41
42
        ################################################################################################################
43
        # Step 1: valid parameters
44
        ################################################################################################################
45
        if tenant_id is None:
46
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_TENANT_ID')
47
        else:
48
            tenant_id = str.strip(tenant_id)
49
            if not tenant_id.isdigit() or int(tenant_id) <= 0:
50
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_TENANT_ID')
51
52
        if period_type is None:
53
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
54
        else:
55
            period_type = str.strip(period_type)
56
            if period_type not in ['hourly', 'daily', 'monthly', 'yearly']:
57
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
58
59
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
60
        if config.utc_offset[0] == '-':
61
            timezone_offset = -timezone_offset
62
63
        base_start_datetime_utc = None
64
        if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0:
65
            base_start_datetime_local = str.strip(base_start_datetime_local)
66
            try:
67
                base_start_datetime_utc = datetime.strptime(base_start_datetime_local,
68
                                                            '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
69
                    timedelta(minutes=timezone_offset)
70
            except ValueError:
71
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
72
                                       description="API.INVALID_BASE_PERIOD_BEGINS_DATETIME")
73
74
        base_end_datetime_utc = None
75
        if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0:
76
            base_end_datetime_local = str.strip(base_end_datetime_local)
77
            try:
78
                base_end_datetime_utc = datetime.strptime(base_end_datetime_local,
79
                                                          '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
80
                    timedelta(minutes=timezone_offset)
81
            except ValueError:
82
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
83
                                       description="API.INVALID_BASE_PERIOD_ENDS_DATETIME")
84
85
        if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \
86
                base_start_datetime_utc >= base_end_datetime_utc:
87
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
88
                                   description='API.INVALID_BASE_PERIOD_ENDS_DATETIME')
89
90
        if reporting_start_datetime_local is None:
91
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
92
                                   description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME")
93
        else:
94
            reporting_start_datetime_local = str.strip(reporting_start_datetime_local)
95
            try:
96
                reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local,
97
                                                                 '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
98
                    timedelta(minutes=timezone_offset)
99
            except ValueError:
100
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
101
                                       description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME")
102
103
        if reporting_end_datetime_local is None:
104
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
105
                                   description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME")
106
        else:
107
            reporting_end_datetime_local = str.strip(reporting_end_datetime_local)
108
            try:
109
                reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local,
110
                                                               '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
111
                    timedelta(minutes=timezone_offset)
112
            except ValueError:
113
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
114
                                       description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME")
115
116
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
117
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
118
                                   description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME')
119
120
        ################################################################################################################
121
        # Step 2: query the tenant
122
        ################################################################################################################
123
        cnx_system = mysql.connector.connect(**config.myems_system_db)
124
        cursor_system = cnx_system.cursor()
125
126
        cnx_energy = mysql.connector.connect(**config.myems_energy_db)
127
        cursor_energy = cnx_energy.cursor()
128
129
        cnx_historical = mysql.connector.connect(**config.myems_historical_db)
130
        cursor_historical = cnx_historical.cursor()
131
132
        cursor_system.execute(" SELECT id, name, area, cost_center_id "
133
                              " FROM tbl_tenants "
134
                              " WHERE id = %s ", (tenant_id,))
135
        row_tenant = cursor_system.fetchone()
136
        if row_tenant is None:
137
            if cursor_system:
138
                cursor_system.close()
139
            if cnx_system:
140
                cnx_system.disconnect()
141
142
            if cursor_energy:
143
                cursor_energy.close()
144
            if cnx_energy:
145
                cnx_energy.disconnect()
146
147
            if cnx_historical:
148
                cnx_historical.close()
149
            if cursor_historical:
150
                cursor_historical.disconnect()
151
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.TENANT_NOT_FOUND')
152
153
        tenant = dict()
154
        tenant['id'] = row_tenant[0]
155
        tenant['name'] = row_tenant[1]
156
        tenant['area'] = row_tenant[2]
157
        tenant['cost_center_id'] = row_tenant[3]
158
159
        ################################################################################################################
160
        # Step 3: query energy categories
161
        ################################################################################################################
162
        energy_category_set = set()
163
        # query energy categories in base period
164
        cursor_energy.execute(" SELECT DISTINCT(energy_category_id) "
165
                              " FROM tbl_tenant_input_category_hourly "
166
                              " WHERE tenant_id = %s "
167
                              "     AND start_datetime_utc >= %s "
168
                              "     AND start_datetime_utc < %s ",
169
                              (tenant['id'], base_start_datetime_utc, base_end_datetime_utc))
170
        rows_energy_categories = cursor_energy.fetchall()
171
        if rows_energy_categories is not None or len(rows_energy_categories) > 0:
172
            for row_energy_category in rows_energy_categories:
173
                energy_category_set.add(row_energy_category[0])
174
175
        # query energy categories in reporting period
176
        cursor_energy.execute(" SELECT DISTINCT(energy_category_id) "
177
                              " FROM tbl_tenant_input_category_hourly "
178
                              " WHERE tenant_id = %s "
179
                              "     AND start_datetime_utc >= %s "
180
                              "     AND start_datetime_utc < %s ",
181
                              (tenant['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
182
        rows_energy_categories = cursor_energy.fetchall()
183
        if rows_energy_categories is not None or len(rows_energy_categories) > 0:
184
            for row_energy_category in rows_energy_categories:
185
                energy_category_set.add(row_energy_category[0])
186
187
        # query all energy categories in base period and reporting period
188
        cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e "
189
                              " FROM tbl_energy_categories "
190
                              " ORDER BY id ", )
191
        rows_energy_categories = cursor_system.fetchall()
192
        if rows_energy_categories is None or len(rows_energy_categories) == 0:
193
            if cursor_system:
194
                cursor_system.close()
195
            if cnx_system:
196
                cnx_system.disconnect()
197
198
            if cursor_energy:
199
                cursor_energy.close()
200
            if cnx_energy:
201
                cnx_energy.disconnect()
202
203
            if cnx_historical:
204
                cnx_historical.close()
205
            if cursor_historical:
206
                cursor_historical.disconnect()
207
            raise falcon.HTTPError(falcon.HTTP_404,
208
                                   title='API.NOT_FOUND',
209
                                   description='API.ENERGY_CATEGORY_NOT_FOUND')
210
        energy_category_dict = dict()
211
        for row_energy_category in rows_energy_categories:
212
            if row_energy_category[0] in energy_category_set:
213
                energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1],
214
                                                                "unit_of_measure": row_energy_category[2],
215
                                                                "kgce": row_energy_category[3],
216
                                                                "kgco2e": row_energy_category[4]}
217
218
        ################################################################################################################
219
        # Step 4: query associated sensors
220
        ################################################################################################################
221
        point_list = list()
222
        cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type  "
223
                              " FROM tbl_tenants t, tbl_sensors s, tbl_tenants_sensors ts, "
224
                              "      tbl_points p, tbl_sensors_points sp "
225
                              " WHERE t.id = %s AND t.id = ts.tenant_id AND ts.sensor_id = s.id "
226
                              "       AND s.id = sp.sensor_id AND sp.point_id = p.id "
227
                              " ORDER BY p.id ", (tenant['id'], ))
228
        rows_points = cursor_system.fetchall()
229
        if rows_points is not None and len(rows_points) > 0:
230
            for row in rows_points:
231
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
232
233
        ################################################################################################################
234
        # Step 5: query associated points
235
        ################################################################################################################
236
        cursor_system.execute(" SELECT p.id, p.name, p.units, p.object_type  "
237
                              " FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p "
238
                              " WHERE t.id = %s AND t.id = tp.tenant_id AND tp.point_id = p.id "
239
                              " ORDER BY p.id ", (tenant['id'], ))
240
        rows_points = cursor_system.fetchall()
241
        if rows_points is not None and len(rows_points) > 0:
242
            for row in rows_points:
243
                point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
244
245
        ################################################################################################################
246
        # Step 6: query base period energy input
247
        ################################################################################################################
248
        base = dict()
249
        if energy_category_set is not None and len(energy_category_set) > 0:
250
            for energy_category_id in energy_category_set:
251
                base[energy_category_id] = dict()
252
                base[energy_category_id]['timestamps'] = list()
253
                base[energy_category_id]['values'] = list()
254
                base[energy_category_id]['subtotal'] = Decimal(0.0)
255
                base[energy_category_id]['mean'] = None
256
                base[energy_category_id]['median'] = None
257
                base[energy_category_id]['minimum'] = None
258
                base[energy_category_id]['maximum'] = None
259
                base[energy_category_id]['stdev'] = None
260
                base[energy_category_id]['variance'] = None
261
262
                cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
263
                                      " FROM tbl_tenant_input_category_hourly "
264
                                      " WHERE tenant_id = %s "
265
                                      "     AND energy_category_id = %s "
266
                                      "     AND start_datetime_utc >= %s "
267
                                      "     AND start_datetime_utc < %s "
268
                                      " ORDER BY start_datetime_utc ",
269
                                      (tenant['id'],
270
                                       energy_category_id,
271
                                       base_start_datetime_utc,
272
                                       base_end_datetime_utc))
273
                rows_tenant_hourly = cursor_energy.fetchall()
274
275
                rows_tenant_periodically, \
276
                    base[energy_category_id]['mean'], \
277
                    base[energy_category_id]['median'], \
278
                    base[energy_category_id]['minimum'], \
279
                    base[energy_category_id]['maximum'], \
280
                    base[energy_category_id]['stdev'], \
281
                    base[energy_category_id]['variance'] = \
282
                    utilities.statistics_hourly_data_by_period(rows_tenant_hourly,
283
                                                               base_start_datetime_utc,
284
                                                               base_end_datetime_utc,
285
                                                               period_type)
286
287
                for row_tenant_periodically in rows_tenant_periodically:
288
                    current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \
289
                                             timedelta(minutes=timezone_offset)
290
                    if period_type == 'hourly':
291
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
292
                    elif period_type == 'daily':
293
                        current_datetime = current_datetime_local.strftime('%Y-%m-%d')
294
                    elif period_type == 'monthly':
295
                        current_datetime = current_datetime_local.strftime('%Y-%m')
296
                    elif period_type == 'yearly':
297
                        current_datetime = current_datetime_local.strftime('%Y')
298
299
                    actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1]
300
                    base[energy_category_id]['timestamps'].append(current_datetime)
0 ignored issues
show
introduced by
The variable current_datetime does not seem to be defined for all execution paths.
Loading history...
301
                    base[energy_category_id]['values'].append(actual_value)
302
                    base[energy_category_id]['subtotal'] += actual_value
303
304
        ################################################################################################################
305
        # Step 7: query reporting period energy input
306
        ################################################################################################################
307
        reporting = dict()
308
        if energy_category_set is not None and len(energy_category_set) > 0:
309
            for energy_category_id in energy_category_set:
310
                reporting[energy_category_id] = dict()
311
                reporting[energy_category_id]['timestamps'] = list()
312
                reporting[energy_category_id]['values'] = list()
313
                reporting[energy_category_id]['subtotal'] = Decimal(0.0)
314
                reporting[energy_category_id]['mean'] = None
315
                reporting[energy_category_id]['median'] = None
316
                reporting[energy_category_id]['minimum'] = None
317
                reporting[energy_category_id]['maximum'] = None
318
                reporting[energy_category_id]['stdev'] = None
319
                reporting[energy_category_id]['variance'] = None
320
321
                cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
322
                                      " FROM tbl_tenant_input_category_hourly "
323
                                      " WHERE tenant_id = %s "
324
                                      "     AND energy_category_id = %s "
325
                                      "     AND start_datetime_utc >= %s "
326
                                      "     AND start_datetime_utc < %s "
327
                                      " ORDER BY start_datetime_utc ",
328
                                      (tenant['id'],
329
                                       energy_category_id,
330
                                       reporting_start_datetime_utc,
331
                                       reporting_end_datetime_utc))
332
                rows_tenant_hourly = cursor_energy.fetchall()
333
334
                rows_tenant_periodically, \
335
                    reporting[energy_category_id]['mean'], \
336
                    reporting[energy_category_id]['median'], \
337
                    reporting[energy_category_id]['minimum'], \
338
                    reporting[energy_category_id]['maximum'], \
339
                    reporting[energy_category_id]['stdev'], \
340
                    reporting[energy_category_id]['variance'] = \
341
                    utilities.statistics_hourly_data_by_period(rows_tenant_hourly,
342
                                                               reporting_start_datetime_utc,
343
                                                               reporting_end_datetime_utc,
344
                                                               period_type)
345
346
                for row_tenant_periodically in rows_tenant_periodically:
347
                    current_datetime_local = row_tenant_periodically[0].replace(tzinfo=timezone.utc) + \
348
                                             timedelta(minutes=timezone_offset)
349
                    if period_type == 'hourly':
350
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
351
                    elif period_type == 'daily':
352
                        current_datetime = current_datetime_local.strftime('%Y-%m-%d')
353
                    elif period_type == 'monthly':
354
                        current_datetime = current_datetime_local.strftime('%Y-%m')
355
                    elif period_type == 'yearly':
356
                        current_datetime = current_datetime_local.strftime('%Y')
357
358
                    actual_value = Decimal(0.0) if row_tenant_periodically[1] is None else row_tenant_periodically[1]
359
                    reporting[energy_category_id]['timestamps'].append(current_datetime)
360
                    reporting[energy_category_id]['values'].append(actual_value)
361
                    reporting[energy_category_id]['subtotal'] += actual_value
362
363
        ################################################################################################################
364
        # Step 8: query tariff data
365
        ################################################################################################################
366
        parameters_data = dict()
367
        parameters_data['names'] = list()
368
        parameters_data['timestamps'] = list()
369
        parameters_data['values'] = list()
370
        if energy_category_set is not None and len(energy_category_set) > 0:
371
            for energy_category_id in energy_category_set:
372
                energy_category_tariff_dict = utilities.get_energy_category_tariffs(tenant['cost_center_id'],
373
                                                                                    energy_category_id,
374
                                                                                    reporting_start_datetime_utc,
375
                                                                                    reporting_end_datetime_utc)
376
                tariff_timestamp_list = list()
377
                tariff_value_list = list()
378
                for k, v in energy_category_tariff_dict.items():
379
                    # convert k from utc to local
380
                    k = k + timedelta(minutes=timezone_offset)
381
                    tariff_timestamp_list.append(k.isoformat()[0:19][0:19])
382
                    tariff_value_list.append(v)
383
384
                parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name'])
385
                parameters_data['timestamps'].append(tariff_timestamp_list)
386
                parameters_data['values'].append(tariff_value_list)
387
388
        ################################################################################################################
389
        # Step 9: query associated sensors and points data
390
        ################################################################################################################
391
        for point in point_list:
392
            point_values = []
393
            point_timestamps = []
394
            if point['object_type'] == 'ANALOG_VALUE':
395
                query = (" SELECT utc_date_time, actual_value "
396
                         " FROM tbl_analog_value "
397
                         " WHERE point_id = %s "
398
                         "       AND utc_date_time BETWEEN %s AND %s "
399
                         " ORDER BY utc_date_time ")
400
                cursor_historical.execute(query, (point['id'],
401
                                                  reporting_start_datetime_utc,
402
                                                  reporting_end_datetime_utc))
403
                rows = cursor_historical.fetchall()
404
405
                if rows is not None and len(rows) > 0:
406
                    for row in rows:
407
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
408
                                                 timedelta(minutes=timezone_offset)
409
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
410
                        point_timestamps.append(current_datetime)
411
                        point_values.append(row[1])
412
413
            elif point['object_type'] == 'ENERGY_VALUE':
414
                query = (" SELECT utc_date_time, actual_value "
415
                         " FROM tbl_energy_value "
416
                         " WHERE point_id = %s "
417
                         "       AND utc_date_time BETWEEN %s AND %s "
418
                         " ORDER BY utc_date_time ")
419
                cursor_historical.execute(query, (point['id'],
420
                                                  reporting_start_datetime_utc,
421
                                                  reporting_end_datetime_utc))
422
                rows = cursor_historical.fetchall()
423
424
                if rows is not None and len(rows) > 0:
425
                    for row in rows:
426
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
427
                                                 timedelta(minutes=timezone_offset)
428
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
429
                        point_timestamps.append(current_datetime)
430
                        point_values.append(row[1])
431
            elif point['object_type'] == 'DIGITAL_VALUE':
432
                query = (" SELECT utc_date_time, actual_value "
433
                         " FROM tbl_digital_value "
434
                         " WHERE point_id = %s "
435
                         "       AND utc_date_time BETWEEN %s AND %s ")
436
                cursor_historical.execute(query, (point['id'],
437
                                                  reporting_start_datetime_utc,
438
                                                  reporting_end_datetime_utc))
439
                rows = cursor_historical.fetchall()
440
441
                if rows is not None and len(rows) > 0:
442
                    for row in rows:
443
                        current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
444
                                                 timedelta(minutes=timezone_offset)
445
                        current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
446
                        point_timestamps.append(current_datetime)
447
                        point_values.append(row[1])
448
449
            parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
450
            parameters_data['timestamps'].append(point_timestamps)
451
            parameters_data['values'].append(point_values)
452
453
        ################################################################################################################
454
        # Step 10: construct the report
455
        ################################################################################################################
456
        if cursor_system:
457
            cursor_system.close()
458
        if cnx_system:
459
            cnx_system.disconnect()
460
461
        if cursor_energy:
462
            cursor_energy.close()
463
        if cnx_energy:
464
            cnx_energy.disconnect()
465
466
        result = dict()
467
468
        result['tenant'] = dict()
469
        result['tenant']['name'] = tenant['name']
470
        result['tenant']['area'] = tenant['area']
471
472
        result['base_period'] = dict()
473
        result['base_period']['names'] = list()
474
        result['base_period']['units'] = list()
475
        result['base_period']['timestamps'] = list()
476
        result['base_period']['values'] = list()
477
        result['base_period']['subtotals'] = list()
478
        result['base_period']['means'] = list()
479
        result['base_period']['medians'] = list()
480
        result['base_period']['minimums'] = list()
481
        result['base_period']['maximums'] = list()
482
        result['base_period']['stdevs'] = list()
483
        result['base_period']['variances'] = list()
484
485
        if energy_category_set is not None and len(energy_category_set) > 0:
486
            for energy_category_id in energy_category_set:
487
                result['base_period']['names'].append(energy_category_dict[energy_category_id]['name'])
488
                result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
489
                result['base_period']['timestamps'].append(base[energy_category_id]['timestamps'])
490
                result['base_period']['values'].append(base[energy_category_id]['values'])
491
                result['base_period']['subtotals'].append(base[energy_category_id]['subtotal'])
492
                result['base_period']['means'].append(base[energy_category_id]['mean'])
493
                result['base_period']['medians'].append(base[energy_category_id]['median'])
494
                result['base_period']['minimums'].append(base[energy_category_id]['minimum'])
495
                result['base_period']['maximums'].append(base[energy_category_id]['maximum'])
496
                result['base_period']['stdevs'].append(base[energy_category_id]['stdev'])
497
                result['base_period']['variances'].append(base[energy_category_id]['variance'])
498
499
        result['reporting_period'] = dict()
500
        result['reporting_period']['names'] = list()
501
        result['reporting_period']['energy_category_ids'] = list()
502
        result['reporting_period']['units'] = list()
503
        result['reporting_period']['timestamps'] = list()
504
        result['reporting_period']['values'] = list()
505
        result['reporting_period']['subtotals'] = list()
506
        result['reporting_period']['means'] = list()
507
        result['reporting_period']['means_per_unit_area'] = list()
508
        result['reporting_period']['means_increment_rate'] = list()
509
        result['reporting_period']['medians'] = list()
510
        result['reporting_period']['medians_per_unit_area'] = list()
511
        result['reporting_period']['medians_increment_rate'] = list()
512
        result['reporting_period']['minimums'] = list()
513
        result['reporting_period']['minimums_per_unit_area'] = list()
514
        result['reporting_period']['minimums_increment_rate'] = list()
515
        result['reporting_period']['maximums'] = list()
516
        result['reporting_period']['maximums_per_unit_area'] = list()
517
        result['reporting_period']['maximums_increment_rate'] = list()
518
        result['reporting_period']['stdevs'] = list()
519
        result['reporting_period']['stdevs_per_unit_area'] = list()
520
        result['reporting_period']['stdevs_increment_rate'] = list()
521
        result['reporting_period']['variances'] = list()
522
        result['reporting_period']['variances_per_unit_area'] = list()
523
        result['reporting_period']['variances_increment_rate'] = list()
524
525
        if energy_category_set is not None and len(energy_category_set) > 0:
526
            for energy_category_id in energy_category_set:
527
                result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name'])
528
                result['reporting_period']['energy_category_ids'].append(energy_category_id)
529
                result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
530
                result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps'])
531
                result['reporting_period']['values'].append(reporting[energy_category_id]['values'])
532
                result['reporting_period']['subtotals'].append(reporting[energy_category_id]['subtotal'])
533
                result['reporting_period']['means'].append(reporting[energy_category_id]['mean'])
534
                result['reporting_period']['means_per_unit_area'].append(
535
                    reporting[energy_category_id]['mean'] / tenant['area']
536
                    if reporting[energy_category_id]['mean'] is not None and
537
                    tenant['area'] is not None and
538
                    tenant['area'] > Decimal(0.0)
539
                    else None)
540
                result['reporting_period']['means_increment_rate'].append(
541
                    (reporting[energy_category_id]['mean'] - base[energy_category_id]['mean']) /
542
                    base[energy_category_id]['mean'] if (base[energy_category_id]['mean'] is not None and
543
                                                         base[energy_category_id]['mean'] > Decimal(0.0))
544
                    else None)
545
                result['reporting_period']['medians'].append(reporting[energy_category_id]['median'])
546
                result['reporting_period']['medians_per_unit_area'].append(
547
                    reporting[energy_category_id]['median'] / tenant['area']
548
                    if reporting[energy_category_id]['median'] is not None and
549
                    tenant['area'] is not None and
550
                    tenant['area'] > Decimal(0.0)
551
                    else None)
552
                result['reporting_period']['medians_increment_rate'].append(
553
                    (reporting[energy_category_id]['median'] - base[energy_category_id]['median']) /
554
                    base[energy_category_id]['median'] if (base[energy_category_id]['median'] is not None and
555
                                                           base[energy_category_id]['median'] > Decimal(0.0))
556
                    else None)
557
                result['reporting_period']['minimums'].append(reporting[energy_category_id]['minimum'])
558
                result['reporting_period']['minimums_per_unit_area'].append(
559
                    reporting[energy_category_id]['minimum'] / tenant['area']
560
                    if reporting[energy_category_id]['minimum'] is not None and
561
                    tenant['area'] is not None and
562
                    tenant['area'] > Decimal(0.0)
563
                    else None)
564
                result['reporting_period']['minimums_increment_rate'].append(
565
                    (reporting[energy_category_id]['minimum'] - base[energy_category_id]['minimum']) /
566
                    base[energy_category_id]['minimum'] if (base[energy_category_id]['minimum'] is not None and
567
                                                            base[energy_category_id]['minimum'] > Decimal(0.0))
568
                    else None)
569
                result['reporting_period']['maximums'].append(reporting[energy_category_id]['maximum'])
570
                result['reporting_period']['maximums_per_unit_area'].append(
571
                    reporting[energy_category_id]['maximum'] / tenant['area']
572
                    if reporting[energy_category_id]['maximum'] is not None and
573
                    tenant['area'] is not None and
574
                    tenant['area'] > Decimal(0.0)
575
                    else None)
576
                result['reporting_period']['maximums_increment_rate'].append(
577
                    (reporting[energy_category_id]['maximum'] - base[energy_category_id]['maximum']) /
578
                    base[energy_category_id]['maximum'] if (base[energy_category_id]['maximum'] is not None and
579
                                                            base[energy_category_id]['maximum'] > Decimal(0.0))
580
                    else None)
581
                result['reporting_period']['stdevs'].append(reporting[energy_category_id]['stdev'])
582
                result['reporting_period']['stdevs_per_unit_area'].append(
583
                    reporting[energy_category_id]['stdev'] / tenant['area']
584
                    if reporting[energy_category_id]['stdev'] is not None and
585
                    tenant['area'] is not None and
586
                    tenant['area'] > Decimal(0.0)
587
                    else None)
588
                result['reporting_period']['stdevs_increment_rate'].append(
589
                    (reporting[energy_category_id]['stdev'] - base[energy_category_id]['stdev']) /
590
                    base[energy_category_id]['stdev'] if (base[energy_category_id]['stdev'] is not None and
591
                                                          base[energy_category_id]['stdev'] > Decimal(0.0))
592
                    else None)
593
                result['reporting_period']['variances'].append(reporting[energy_category_id]['variance'])
594
                result['reporting_period']['variances_per_unit_area'].append(
595
                    reporting[energy_category_id]['variance'] / tenant['area']
596
                    if reporting[energy_category_id]['variance'] is not None and
597
                    tenant['area'] is not None and
598
                    tenant['area'] > Decimal(0.0)
599
                    else None)
600
                result['reporting_period']['variances_increment_rate'].append(
601
                    (reporting[energy_category_id]['variance'] - base[energy_category_id]['variance']) /
602
                    base[energy_category_id]['variance'] if (base[energy_category_id]['variance'] is not None and
603
                                                             base[energy_category_id]['variance'] > Decimal(0.0))
604
                    else None)
605
606
        result['parameters'] = {
607
            "names": parameters_data['names'],
608
            "timestamps": parameters_data['timestamps'],
609
            "values": parameters_data['values']
610
        }
611
612
        resp.body = json.dumps(result)
613