mzufferey commited on
Commit
1a02e7a
·
1 Parent(s): 8b3534a
app.py CHANGED
@@ -40,24 +40,15 @@ app = dash.Dash(__name__,
40
  external_stylesheets=[dbc.themes.BOOTSTRAP, FONT_AWESOME],
41
  suppress_callback_exceptions=True
42
  )
43
-
44
- # register_dashboard_common(app)
45
  register_répartFréq(app)
46
  register_render_content(app)
47
  register_chargedécharge(app)
48
- # register_appareils(app)
49
  register_timeevo(app)
50
- # register_stat(app)
51
- # register_fonctions(app)
52
- #register_data(app)
53
- # register_dashboard(app)
54
  register_accueil(app)
55
 
56
  # Définir la mise en page de l'application
57
-
58
  all_confirm_dialogs = [dcc.ConfirmDialog(id=x,message='')
59
  for x in all_confirm_dialogs]
60
-
61
  all_maxvar_dialogs = [dcc.ConfirmDialog(id=x,message=popupmsg_maxvar)
62
  for x in ['confirm-dialog-evotime',
63
  'confirm-dialog-daydataP',
@@ -69,8 +60,6 @@ all_times = list(set(time_df[db_timecol]))
69
  all_range_pickers = [get_range_picker(x, all_dates) for x in all_range_pickers]
70
 
71
  app.layout = html.Div([
72
-
73
-
74
  dbc.Modal(
75
  [
76
  dbc.ModalHeader("Graph Full Screen"),
@@ -232,152 +221,6 @@ dcc.Store(id='stored_dashDay_dropdownval', data=None),
232
  ], width=2),
233
 
234
  ]),
235
-
236
- # dbc.Container([
237
- # dbc.Row([
238
- # dbc.Col([
239
- # html.P([
240
- # html.B("Dashboard"),
241
- # " : vue d'ensemble des données disponibles ; "+
242
- # "cliquer sur chacune des variables pour rapidement avoir un aperçu la tendance dans le temps.",
243
- # html.Ul([html.Li(["Pour les ",
244
- # get_nav_link("landpage-dashb-minutes-link", "Données minutes"),
245
- # ""]),
246
- # html.Li(["Pour les ",
247
- # get_nav_link("landpage-dashb-dayI-link", "Données journalières I"),
248
- # ""])
249
- # ]),
250
- # ]),
251
- # get_navbtn(lab="Dashboard", id='landpage-btn-dashboard')
252
- # ], width=4),
253
- #
254
- # dbc.Col([
255
- # dcc.Markdown("""
256
- # **Évolution temporelle** : choisir une base de données puis une ou plusieurs (max. 4) variables ;
257
- # visualisation à choix (line, bar, box).
258
- # """),
259
- # get_navbtn(lab="Évolution temporelle", id='landpage-btn-evotime')
260
- # ], width=4),
261
- #
262
- # dbc.Col([
263
- # dcc.Markdown("""
264
- # **Statistiques - A SUPPRIMER ?** : choisir la table de données, une variable de cette table et le type de visualisation ;
265
- # renvoie également les valeurs moyennes.
266
- # """),
267
- # get_navbtn(lab="Statistiques", id='landpage-btn-stat')
268
- #
269
- # ], width=4)
270
- # ]),
271
- #
272
- # html.Hr(), # Ligne de séparation
273
- #
274
- # dbc.Row([
275
- # dbc.Col([
276
- # dcc.Markdown("""
277
- # **Analyse (Graphes) - A SUPPRIMER ???** : visualiser la répartition des fréquences XT_Fin_Hz_I3122 (L1, L2, L1+L2 à choix) (diagramme camembert)
278
- # ainsi que la température moyenne de la batterie (barplot).
279
- # """),
280
- # get_navbtn(lab="Analyse (Graphes)", id='landpage-btn-analyseGraph')
281
- # ], width=4),
282
- #
283
- # dbc.Col([
284
- #
285
- # html.P([
286
- # html.B("Par appareil"),
287
- # " : visualiser les principaux paramètre pour chacun des appareils."
288
- # "",
289
- # html.Ul([html.Li(["Pour ",
290
- # get_nav_link("landpage-appareil-bsp-link",
291
- # "BSP"),
292
- # """
293
- # (ligne temporelle avec qt 0.1 et 0.9 pour BSP_Ubat_Vdc_I7030_1, BSP_Ibat_Adc_I7031_1, BSP_Tbat_C_I7033_1 avec sa moyenne journalière ;
294
- # pour I7007_1 et I7008_1 : ligne temporelle avec mise en évidence des aires de différence,
295
- # barplot avec mise en évidence du surplus de l'un par rapport à l'autre,
296
- # ligne de delta I7008_1 - I7007_1,
297
- # barplot de rendement 100*I7008_1/I7007_1,
298
- # barplot nombre de cycles à 50% I7007_1/90)
299
- # """]),
300
- # html.Li(["Pour ",
301
- # get_nav_link("landpage-appareil-variotrack-link",
302
- # "Variotrack"),
303
- # """
304
- # (ligne temporelle avec qt 0.1 et 0.9 pour VT_PsoM_kW_I11043_1 et VT_PsoM_kW_I11043_ALL,
305
- # ligne temporelle avec qt 0.1 et 0.9 pour VT_IbaM_Adc_I11040_1,
306
- # ligne temporelle avec qt 0.1 et 0.9 pour I11006_1 et I11007_1)
307
- # """]),
308
- # ]),
309
- # ]),
310
- # get_navbtn(lab="Par appareil", id='landpage-btn-appareils')
311
- #
312
- # ], width=4),
313
- # dbc.Col([
314
- # html.P([
315
- # html.B("Par appareil (suite)"),
316
- # " : visualiser les principaux paramètre pour chacun des appareils."
317
- # "",
318
- # html.Ul([
319
- #
320
- # html.Li(["Pour ",
321
- # get_nav_link("landpage-appareil-xtender-link",
322
- # "Xtender"),
323
- # """
324
- # (lignes temporelles avec 0.1 et 0.9 qt pour XT_Ubat_MIN_Vdc_I3090_L1 et XT_Ubat_MIN_Vdc_I3090_L2,
325
- # lignes temporelles avec 0.1 et 0.9 qt pour XT_Uin_Vac_I3113_L1 et XT_Uin_Vac_I3113_L2,
326
- # lignes temporelles avec aires colorées pour XT_Pout_kVA_I3097_L1 et XT_Pout_kVA_I3097_L1,
327
- # lignes temporelles avec aires colorées pour XT_Iin_Aac_I3116_L1 et XT_Iin_Aac_I3116_L2,
328
- # XT_Fin_Hz_I3122_L1 et XT_Fin_Hz_I3122_L2 : barplots verticalement superposés pour différencier la répartition des sources, stacked barplots répartition des sources par jour
329
- # side-by-side barplot pour I3081_1 et I3081_2)
330
- #
331
- # """])
332
- # ]),
333
- # ]),
334
- # get_navbtn(lab="Par appareil", id='landpage-btn-appareils2')
335
- #
336
- # ], width=4)
337
- #
338
- # ]),
339
- #
340
- # html.Hr(), # Ligne de séparation
341
- #
342
- # dbc.Row([
343
- # dbc.Col([
344
- #
345
- # html.P([
346
- # html.B("Par fonction - TODO / IN PROGRESS"),
347
- # " : pour visualiser les données en fonction de leur utilisation dans le système ",
348
- # html.Ul([html.Li(["Le sous-onglet ",
349
- # # html.A("Export", id="export-link", href="#",
350
- # # style={"color": "#2507cf", "cursor": "pointer"}),
351
- # get_nav_link("landpage-fct-batterie-link", "Batterie"),
352
- # """ pour voir les données relative au fonctionnement de la batterie
353
- # (lignes temporelles avec quantiles pour XT_Ubat_Vdc_I3092_L1_1 et XT_Ubat_Vdc_I3092_L2_2 ;
354
- # lignes temporelles avec quantiles pour I7007_1 et I7008_1
355
- # """])
356
- # ]),
357
- # ]),
358
- # get_navbtn(lab="Par fonction", id='landpage-btn-fonctions')], width=4),
359
- #
360
- #
361
- # dbc.Col([
362
- # html.P([
363
- # html.B("Données")," : Gérer, ajouter ou exporter des données de la base de données. ",
364
- # "Obtenez un aperçu des tables disponibles. ",
365
- # html.Ul([
366
- # html.Li(["Le sous-onglet pour ",
367
- # get_nav_link("landpage-data-manage-link", "Gérer les données"),
368
- # " permet d'ajouter (fichier(s) csv) ou supprimer des données de la base de données."]),
369
- # html.Li(["Le sous-onglet pour ",
370
- # get_nav_link("landpage-data-export-link", "Exporter des données"),
371
- # " permet de télécharger les données pour une période sélectionnée (.xlsx) ou la base donnée complète (.db)."]),
372
- # html.Li(["Le sous-onglet ",
373
- # get_nav_link("landpage-data-overview-link", "Aperçu"),
374
- # " permet d'afficher une partie du contenu de la base de données."])
375
- # ], ),
376
- # ]),
377
- # get_navbtn(lab="Données" ,id='landpage-btn-data')
378
- #
379
- # ], width=4)
380
- # ])
381
  ], fluid=True)
382
  ], style={'padding': '40px', 'backgroundColor': '#f8f9fa'})
383
  ]),
@@ -425,25 +268,15 @@ dcc.Store(id='stored_dashDay_dropdownval', data=None),
425
  # Callback pour gérer la navigation vers les onglets et sous-onglets
426
  @app.callback(
427
  [Output('tabs-example', 'value'),
428
- # Output('subtabs-appareils', 'value'),
429
  Output('subtabs-data', 'value')],
430
- # [Input('landpage-btn-dashboard', 'n_clicks'),
431
- [Input('landpage-btn-evotime', 'n_clicks'),
432
  Input('landpage-btn-stat', 'n_clicks'),
433
  Input('landpage-btn-analyseGraph', 'n_clicks'),
434
- # Input('landpage-btn-appareils', 'n_clicks'),
435
- # Input('landpage-btn-appareils2', 'n_clicks'),
436
- # Input('landpage-appareil-variotrack-link', 'n_clicks'),
437
- # Input('landpage-btn-fonctions', 'n_clicks'),
438
- Input('landpage-btn-data', 'n_clicks'),
439
  Input('landpage-data-export-link', 'n_clicks'),
440
  Input('landpage-data-overview-link', 'n_clicks'),
441
- Input('landpage-data-manage-link', 'n_clicks'),
442
- # Input('landpage-dashb-minutes-link', 'n_clicks'),
443
- # Input('landpage-dashb-dayI-link', 'n_clicks'),
444
- # Input('landpage-appareil-bsp-link', 'n_clicks'),
445
- # Input('landpage-appareil-xtender-link', 'n_clicks'),
446
- ],
447
  [State('tabs-example', 'value')]
448
  )
449
  def navigate_to_tabs_and_subtabs(*args):
@@ -499,11 +332,10 @@ def navigate_to_tabs_and_subtabs(*args):
499
  elif button_id == 'landpage-data-overview-link':
500
  subtab_data_value = 'subtab-showDB'
501
  # Retourner les valeurs des onglets et sous-onglets
502
- # return tab_value, subtab_appareils_value, subtab_data_value
503
  return tab_value, subtab_data_value
504
 
505
  # Exécuter l'application
506
  if __name__ == '__main__':
507
- #app.run_server(debug=True)
508
  # for deploy
509
  app.run(debug=True, host='0.0.0.0', port=7860)
 
40
  external_stylesheets=[dbc.themes.BOOTSTRAP, FONT_AWESOME],
41
  suppress_callback_exceptions=True
42
  )
 
 
43
  register_répartFréq(app)
44
  register_render_content(app)
45
  register_chargedécharge(app)
 
46
  register_timeevo(app)
 
 
 
 
47
  register_accueil(app)
48
 
49
  # Définir la mise en page de l'application
 
50
  all_confirm_dialogs = [dcc.ConfirmDialog(id=x,message='')
51
  for x in all_confirm_dialogs]
 
52
  all_maxvar_dialogs = [dcc.ConfirmDialog(id=x,message=popupmsg_maxvar)
53
  for x in ['confirm-dialog-evotime',
54
  'confirm-dialog-daydataP',
 
60
  all_range_pickers = [get_range_picker(x, all_dates) for x in all_range_pickers]
61
 
62
  app.layout = html.Div([
 
 
63
  dbc.Modal(
64
  [
65
  dbc.ModalHeader("Graph Full Screen"),
 
221
  ], width=2),
222
 
223
  ]),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  ], fluid=True)
225
  ], style={'padding': '40px', 'backgroundColor': '#f8f9fa'})
226
  ]),
 
268
  # Callback pour gérer la navigation vers les onglets et sous-onglets
269
  @app.callback(
270
  [Output('tabs-example', 'value'),
 
271
  Output('subtabs-data', 'value')],
272
+ [Input('landpage-btn-evotime', 'n_clicks'),
 
273
  Input('landpage-btn-stat', 'n_clicks'),
274
  Input('landpage-btn-analyseGraph', 'n_clicks'),
275
+ Input('landpage-btn-data', 'n_clicks'),
 
 
 
 
276
  Input('landpage-data-export-link', 'n_clicks'),
277
  Input('landpage-data-overview-link', 'n_clicks'),
278
+ Input('landpage-data-manage-link', 'n_clicks')
279
+ ],
 
 
 
 
280
  [State('tabs-example', 'value')]
281
  )
282
  def navigate_to_tabs_and_subtabs(*args):
 
332
  elif button_id == 'landpage-data-overview-link':
333
  subtab_data_value = 'subtab-showDB'
334
  # Retourner les valeurs des onglets et sous-onglets
 
335
  return tab_value, subtab_data_value
336
 
337
  # Exécuter l'application
338
  if __name__ == '__main__':
339
+ #app.run_server(debug=True,host='0.0.0.0', port=7860)
340
  # for deploy
341
  app.run(debug=True, host='0.0.0.0', port=7860)
callbacks/common_callbacks.py CHANGED
@@ -4,69 +4,6 @@ from app_settings import *
4
 
5
  all_pickers = ['date-picker-dbdata'] + all_range_pickers
6
 
7
- # def register_callbacks(app):
8
-
9
- ##################################################################################
10
- ######################################### DATE PICKER HANDLING
11
- ##################################################################################
12
- # @app.callback(
13
- # [Output(picker_id, 'style') for picker_id in all_pickers],
14
- # [
15
- # Input('tabs-example', 'value'),
16
- # Input('subtabs-appareils', 'value'),
17
- # Input('subtabs-fonctions', 'value'),
18
- # Input('subtabs-dashboard', 'value'),
19
- # Input('subtabs-data', 'value') ]
20
- # )
21
- # def show_hide_datepickers(tab, subtab_appareils, subtab_fonctions,
22
- # subtab_dashboard, subtab_data):
23
- # # styles = {
24
- # # 'date-picker-dbdata': {'display': 'none'},
25
- # # 'range-picker-evotime': {'display': 'none'},
26
- # # 'range-picker-stat': {'display': 'none'},
27
- # # 'range-picker-analyseGraph': {'display': 'none'},
28
- # # 'range-picker-subxtender': {'display': 'none'},
29
- # # 'range-picker-subvariotrack': {'display': 'none'},
30
- # # 'range-picker-subbsp': {'display': 'none'},
31
- # # 'range-picker-subbat': {'display': 'none'},
32
- # # 'range-picker-subminutes': {'display': 'none'},
33
- # # 'range-picker-subdayI': {'display': 'none'},
34
- # # 'range-picker-exportdata': {'display': 'none'}
35
- # # }
36
- #
37
- # styles = {picker: {'display': 'none'} for picker in all_pickers}
38
- #
39
- # if tab == "tab-data" :
40
- # if subtab_data == 'subtab-showDB':
41
- # styles['date-picker-dbdata'] = {'display': 'block', 'margin': '20px 0'}
42
- # elif subtab_data == 'subtab-exportDB':
43
- # styles['range-picker-exportdata'] = {'display': 'block', 'margin': '20px 0'}
44
- # elif tab == 'tab-evotime':
45
- # styles['range-picker-evotime'] = {'display': 'block', 'margin': '20px 0'}
46
- # elif tab == 'tab-stat':
47
- # styles['range-picker-stat'] = {'display': 'block', 'margin': '20px 0'}
48
- # elif tab == 'tab-analyseGraph':
49
- # styles['range-picker-analyseGraph'] = {'display': 'block', 'margin': '20px 0'}
50
- # elif tab == 'tab-appareils':
51
- # if subtab_appareils == "subtab-xtender":
52
- # styles['range-picker-subxtender'] = {'display': 'block', 'margin': '20px 0'}
53
- # elif subtab_appareils == "subtab-variotrack":
54
- # styles['range-picker-subvariotrack'] = {'display': 'block', 'margin': '20px 0'}
55
- # elif subtab_appareils == "subtab-bsp":
56
- # styles['range-picker-subbsp'] = {'display': 'block', 'margin': '20px 0'}
57
- # elif tab == 'tab-fonctions':
58
- # if subtab_fonctions == "subtab-batterie":
59
- # styles['range-picker-subbat'] = {'display': 'block', 'margin': '20px 0'}
60
- # elif tab == 'tab-dashboard':
61
- # if subtab_dashboard == "subtab-minutesdata":
62
- # styles['range-picker-subminutes'] = {'display': 'block', 'margin': '20px 0'}
63
- # elif subtab_dashboard == "subtab-dayIdata":
64
- # styles['range-picker-subdayI'] = {'display': 'block', 'margin': '20px 0'}
65
- #
66
- # return [styles[key] for key in styles]
67
- #
68
-
69
-
70
  def register_callbacks(app):
71
 
72
  @app.callback(
@@ -211,19 +148,6 @@ def register_callbacks(app):
211
  max_date = max([day_min_date]+[time_min_date])
212
  disabled_days = [x for x in day_disabled_days if x in time_disabled_days]
213
 
214
- # else:
215
- # # Si la base de données sélectionnée n'est ni time ni day, on sort
216
- # min_date, max_date, disabled_days = None, None, []
217
- print("time_min date = ", time_min_date)
218
- print("time_max date = ", time_max_date)
219
- print("disabled_days = ", time_disabled_days)
220
- print("day_min date = ", day_min_date)
221
- print("day_max date = ", day_max_date)
222
- print("daydisabled_days = ", day_disabled_days)
223
-
224
- print("min date = ", min_date)
225
- print("max date = ", max_date)
226
- print("disabled_days = ", disabled_days)
227
 
228
  # 3. Retour des styles et des dates mises à jour pour les DatePickerRange
229
  return (
@@ -241,14 +165,6 @@ def register_callbacks(app):
241
  def update_statperiod_store(selected_period):
242
  return selected_period
243
 
244
- # @app.callback(
245
- # Output('stored_dataShowDB_dropdownval', 'data'),
246
- # Input('statperiod-dropdown', 'value')
247
- # )
248
- # def update_statperiod_store(selected_period):
249
- # return selected_period
250
-
251
-
252
  @app.callback(
253
  Output('stored_dataExportDB_dropdownval', 'data'),
254
  Input('exportdata-period-dropdown', 'value')
 
4
 
5
  all_pickers = ['date-picker-dbdata'] + all_range_pickers
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  def register_callbacks(app):
8
 
9
  @app.callback(
 
148
  max_date = max([day_min_date]+[time_min_date])
149
  disabled_days = [x for x in day_disabled_days if x in time_disabled_days]
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  # 3. Retour des styles et des dates mises à jour pour les DatePickerRange
153
  return (
 
165
  def update_statperiod_store(selected_period):
166
  return selected_period
167
 
 
 
 
 
 
 
 
 
168
  @app.callback(
169
  Output('stored_dataExportDB_dropdownval', 'data'),
170
  Input('exportdata-period-dropdown', 'value')
callbacks/tab_accueil_callbacks.py CHANGED
@@ -39,8 +39,6 @@ def register_callbacks(app):
39
  stored_timeDB_data,
40
  filename, defaut_timeDB_data, defaut_dayDB_data,
41
  stored_dayDB_data):
42
- # return dcc.Markdown(txt,
43
- # dangerously_allow_html=True)
44
  current_time_df = pd.DataFrame(stored_timeDB_data)
45
  current_day_df = pd.DataFrame(stored_dayDB_data)
46
  print(type(current_time_df[db_timecol][0]))
@@ -69,16 +67,21 @@ def register_callbacks(app):
69
 
70
  time_df_uploaded[db_timecol] = pd.to_datetime(time_df_uploaded[db_timecol])
71
  time_df_uploaded[db_daycol] = time_df_uploaded[db_timecol].dt.date
 
 
 
72
 
73
  print("données time loadées : " + str(time_df_uploaded.shape[0]))
74
  day_df_uploaded = pd.concat([x['dayI_data'] for x in new_data],
75
  ignore_index=True)
76
  day_df_uploaded[db_daycol] = pd.to_datetime(day_df_uploaded[db_daycol])
 
77
 
78
  print("données day loadées : " + str(day_df_uploaded.shape[0]))
79
  txt = "current time DB : " + str(time_df_uploaded.shape[0]) + " x " + str(time_df_uploaded.shape[1]) + "\n"
80
  txt += "current day DB : " + str(day_df_uploaded.shape[0]) + " x " + str(day_df_uploaded.shape[1])
81
  newtxt = dcc.Markdown(txt, dangerously_allow_html=True)
 
82
  return ({'display': 'block'}, time_df_uploaded.to_dict(),
83
  day_df_uploaded.to_dict(), newtxt)
84
 
 
39
  stored_timeDB_data,
40
  filename, defaut_timeDB_data, defaut_dayDB_data,
41
  stored_dayDB_data):
 
 
42
  current_time_df = pd.DataFrame(stored_timeDB_data)
43
  current_day_df = pd.DataFrame(stored_dayDB_data)
44
  print(type(current_time_df[db_timecol][0]))
 
67
 
68
  time_df_uploaded[db_timecol] = pd.to_datetime(time_df_uploaded[db_timecol])
69
  time_df_uploaded[db_daycol] = time_df_uploaded[db_timecol].dt.date
70
+ # ne sert à rien car stored en dict !
71
+ # time_df_uploaded = time_df_uploaded.sort_values(by=db_timecol)
72
+ #time_df_uploaded.to_pickle('time_df_uploaded.pkl')
73
 
74
  print("données time loadées : " + str(time_df_uploaded.shape[0]))
75
  day_df_uploaded = pd.concat([x['dayI_data'] for x in new_data],
76
  ignore_index=True)
77
  day_df_uploaded[db_daycol] = pd.to_datetime(day_df_uploaded[db_daycol])
78
+ #day_df_uploaded = day_df_uploaded.sort_values(by=db_daycol)
79
 
80
  print("données day loadées : " + str(day_df_uploaded.shape[0]))
81
  txt = "current time DB : " + str(time_df_uploaded.shape[0]) + " x " + str(time_df_uploaded.shape[1]) + "\n"
82
  txt += "current day DB : " + str(day_df_uploaded.shape[0]) + " x " + str(day_df_uploaded.shape[1])
83
  newtxt = dcc.Markdown(txt, dangerously_allow_html=True)
84
+
85
  return ({'display': 'block'}, time_df_uploaded.to_dict(),
86
  day_df_uploaded.to_dict(), newtxt)
87
 
callbacks/tab_chargedécharge_callbacks.py CHANGED
@@ -49,7 +49,10 @@ def register_callbacks(app):
49
  def display_bsp_graph(n_clicks,start_date, end_date, selected_period, time_db, day_db):
50
  selected_db = dbTime_name
51
  selected_col = "FOO"
52
- df = pd.DataFrame(time_db)
 
 
 
53
 
54
  if n_clicks is None or n_clicks == 0:
55
  return ["", False, "", ""]
@@ -64,26 +67,28 @@ def register_callbacks(app):
64
  start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
65
  end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
66
  else:
67
- start_date, end_date = get_startrange_date_vLatest(df[db_timecol], selected_period)
 
68
 
69
 
70
  date_info = f"Zoom sur les données du {start_date} au {end_date}"
71
 
72
 
73
- if selected_db == dbTime_name:
74
- xcol = db_timecol
75
- else:
76
- xcol = db_daycol
77
- if selected_db == dbDayI_name:
78
- for col in dayI_cols:
79
- df[col] = df[col + "_1"].fillna(0) + df[col + "_2"].fillna(0)
80
  div_container = []
81
 
 
82
 
83
 
84
- dayI_df = pd.DataFrame(day_db)
85
- start_date, end_date = get_startrange_date_vLatest(dayI_df[db_daycol], selected_period)
86
-
87
 
88
  ## le "throughput energy" journalier I7007 [AH] BSP
89
  # Le bilan des Ah chargé et déchargé du jour I7008-I7007 BSP
@@ -107,6 +112,14 @@ def register_callbacks(app):
107
  df=dayI_df.copy()
108
  df['day'] = pd.to_datetime(df['day'])
109
  df.set_index('day', inplace=True)
 
 
 
 
 
 
 
 
110
  plot5 = get_intersectLines_plot(df, db_daycol,
111
  col1=IvarBSP_toplot[0],
112
  col2=IvarBSP_toplot[1],
@@ -231,6 +244,8 @@ def register_callbacks(app):
231
 
232
 
233
  df = pd.DataFrame(time_db)
 
 
234
 
235
  df_day = df[(pd.to_datetime(df[db_timecol]).dt.time >=
236
  datetime.strptime("08:00", "%H:%M").time()) &
 
49
  def display_bsp_graph(n_clicks,start_date, end_date, selected_period, time_db, day_db):
50
  selected_db = dbTime_name
51
  selected_col = "FOO"
52
+
53
+ # df = pd.DataFrame(time_db)
54
+ dayI_df = pd.DataFrame(day_db)
55
+ dayI_df = dayI_df.sort_values(by=db_daycol)
56
 
57
  if n_clicks is None or n_clicks == 0:
58
  return ["", False, "", ""]
 
67
  start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
68
  end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
69
  else:
70
+ #start_date, end_date = get_startrange_date_vLatest(df[db_timecol], selected_period)
71
+ start_date, end_date = get_startrange_date_vLatest(dayI_df[db_daycol], selected_period)
72
 
73
 
74
  date_info = f"Zoom sur les données du {start_date} au {end_date}"
75
 
76
 
77
+ # if selected_db == dbTime_name:
78
+ # xcol = db_timecol
79
+ # else:
80
+ # xcol = db_daycol
81
+ # if selected_db == dbDayI_name:
82
+ # for col in dayI_cols:
83
+ # df[col] = df[col + "_1"].fillna(0) + df[col + "_2"].fillna(0)
84
  div_container = []
85
 
86
+ # df = df.sort_values(by=xcol)
87
 
88
 
89
+ #dayI_df = pd.DataFrame(day_db)
90
+ #start_date, end_date = get_startrange_date_vLatest(dayI_df[db_daycol], selected_period)
91
+ #dayI_df = dayI_df.sort_values(by=db_daycol)
92
 
93
  ## le "throughput energy" journalier I7007 [AH] BSP
94
  # Le bilan des Ah chargé et déchargé du jour I7008-I7007 BSP
 
112
  df=dayI_df.copy()
113
  df['day'] = pd.to_datetime(df['day'])
114
  df.set_index('day', inplace=True)
115
+
116
+ #df.to_pickle('df_charge_décharge.pkl')
117
+ # print("db_daycol = " + db_daycol)
118
+ # print("start_date = " + str(start_date))
119
+ # print("end_date = " + str(end_date))
120
+ # print("IvarBSP_toplot[0] = " + IvarBSP_toplot[0])
121
+ # print("IvarBSP_toplot[1] = " + IvarBSP_toplot[1])
122
+
123
  plot5 = get_intersectLines_plot(df, db_daycol,
124
  col1=IvarBSP_toplot[0],
125
  col2=IvarBSP_toplot[1],
 
244
 
245
 
246
  df = pd.DataFrame(time_db)
247
+ df = df.sort_values(by=db_timecol)
248
+
249
 
250
  df_day = df[(pd.to_datetime(df[db_timecol]).dt.time >=
251
  datetime.strptime("08:00", "%H:%M").time()) &
callbacks/tab_data_callbacks.py CHANGED
@@ -6,8 +6,6 @@ from utils_fcts import *
6
  from app_settings import *
7
 
8
  def register_callbacks(app):
9
-
10
-
11
  ################################################################################################
12
  ################################ CALLBACKS SUBTAB data
13
  ################################################################################################
@@ -172,8 +170,8 @@ def register_callbacks(app):
172
  if selected_period in ['stat_day', 'stat_week', 'stat_month', 'stat_year']:
173
  if start_date != end_date:
174
  return [txtOut("ERREUR"), True, "Choisir une seule date"]
175
- else:
176
- start_date = get_startrange_date(end_date, selected_period)
177
 
178
  if selected_period == 'stat_perso' and start_date == end_date:
179
  return [ txtOut("ERREUR"), True, "Choisir une date différente"]
@@ -238,10 +236,6 @@ def register_callbacks(app):
238
  disabled_days, min_date_allowed,
239
  max_date_allowed, disabled_days)
240
 
241
-
242
-
243
-
244
-
245
  # Callback pour mettre à jour les dates après upload/suppression
246
  @app.callback(
247
  [Output(picker_id, 'min_date_allowed') for picker_id in all_range_pickers] +
@@ -290,16 +284,7 @@ def register_callbacks(app):
290
  time_df = concat_results['new_time_data']
291
  dayi_df = concat_results['new_dayI_data']
292
  all_msg += concat_results['msg']
293
- # children = [
294
- # parse_contents_vConcat(c, n, time_df, dayi_df) for
295
- # c, n in zip(list_of_contents, list_of_names)
296
- # ]
297
- # return children
298
- # concat_results = [parse_contents_vConcat(c, n, time_df, dayi_df) for
299
- # c, n in zip(list_of_contents, list_of_names)]
300
-
301
  print("données ajoutées à la DB")
302
-
303
  return html.Div([all_msg]), time_df.to_dict(),dayi_df.todict()
304
 
305
 
 
6
  from app_settings import *
7
 
8
  def register_callbacks(app):
 
 
9
  ################################################################################################
10
  ################################ CALLBACKS SUBTAB data
11
  ################################################################################################
 
170
  if selected_period in ['stat_day', 'stat_week', 'stat_month', 'stat_year']:
171
  if start_date != end_date:
172
  return [txtOut("ERREUR"), True, "Choisir une seule date"]
173
+ # else:
174
+ # start_date = get_startrange_date(end_date, selected_period)
175
 
176
  if selected_period == 'stat_perso' and start_date == end_date:
177
  return [ txtOut("ERREUR"), True, "Choisir une date différente"]
 
236
  disabled_days, min_date_allowed,
237
  max_date_allowed, disabled_days)
238
 
 
 
 
 
239
  # Callback pour mettre à jour les dates après upload/suppression
240
  @app.callback(
241
  [Output(picker_id, 'min_date_allowed') for picker_id in all_range_pickers] +
 
284
  time_df = concat_results['new_time_data']
285
  dayi_df = concat_results['new_dayI_data']
286
  all_msg += concat_results['msg']
 
 
 
 
 
 
 
 
287
  print("données ajoutées à la DB")
 
288
  return html.Div([all_msg]), time_df.to_dict(),dayi_df.todict()
289
 
290
 
callbacks/tab_grapheàchoix_callbacks.py CHANGED
@@ -6,12 +6,7 @@ from utils_fcts import *
6
  import plotly.express as px
7
 
8
  def register_callbacks(app):
9
-
10
- # dayPdata_columns = get_daydata_columns("P")
11
- # dayIdata_columns = get_daydata_columns("I")
12
- # timedata_columns = get_timedata_columns()
13
  timecols2show = list(showcols_settings.keys())#x for x in timedata_columns if not showcols_settings[x] == "NA"]
14
- # dayPcols2show = [x for x in dayPdata_columns if not x == db_daycol]
15
  dayIcols2show = list(dayIcols_settings.keys())#[x for x in dayIdata_columns if not x == db_daycol]
16
 
17
 
@@ -44,8 +39,6 @@ def register_callbacks(app):
44
  return None
45
  return html.Div([dcc.Markdown(desc_txt,
46
  dangerously_allow_html=True)])
47
-
48
-
49
  # Callback pour gérer l'ouverture et la fermeture de la modale, et l'affichage du graphique
50
  @app.callback(
51
  [Output('evotime-modal-graph-modal', 'is_open'),
@@ -87,10 +80,8 @@ def register_callbacks(app):
87
  selected_period, start_date, end_date, time_db, day_db):
88
  if n_clicks is None or n_clicks == 0:
89
  return [go.Figure(), False, "", ""]
90
-
91
  if (not selected_db or not selected_col or not selected_viz) :
92
- return [go.Figure(), True, "Sélectionnez des données", ""]
93
-
94
  if selected_db == dbTime_name:
95
  df = pd.DataFrame(time_db)
96
  dfcol = db_timecol
@@ -100,6 +91,8 @@ def register_callbacks(app):
100
  else:
101
  sys.exit(1)
102
 
 
 
103
  if selected_period == "stat_perso" and (not start_date or not end_date):
104
  return [go.Figure(), True, "Sélectionnez une date de début et fin", ""]
105
 
@@ -125,6 +118,8 @@ def register_callbacks(app):
125
  for col in dayI_cols:
126
  df[col] = df[col + "_1"].fillna(0) + df[col + "_2"].fillna(0)
127
 
 
 
128
  if selected_viz == "boxplot" and isinstance(selected_col, list) and len(selected_col) > 1:
129
  df_melted = pd.melt(df, id_vars=[db_daycol], value_vars=selected_col,
130
  var_name='variable', value_name='valeur')
@@ -159,6 +154,7 @@ def register_callbacks(app):
159
  )
160
  update_layout_cols(selected_col)
161
  yaxis_layout['title'] = colsettings[selected_col[0]]['lab']
 
162
  fig.update_layout(
163
  xaxis=dict(domain=[0.25, 0.75], showline=True, linewidth=2, linecolor='black'),
164
  yaxis=yaxis_layout,
@@ -236,8 +232,6 @@ def register_callbacks(app):
236
  if selected_db:
237
  if selected_db == dbTime_name:
238
  columns = [{'label': col, 'value': col} for col in timecols2show]
239
- # elif selected_db == dbDayP_name:
240
- # columns = [{'label': col, 'value': col} for col in dayPcols2show]
241
  elif selected_db == dbDayI_name:
242
  columns = [{'label': col + "=" + dayIcols_settings[col]['lab'],
243
  'value': col} for col in dayI_cols + dayIcols2show]
 
6
  import plotly.express as px
7
 
8
  def register_callbacks(app):
 
 
 
 
9
  timecols2show = list(showcols_settings.keys())#x for x in timedata_columns if not showcols_settings[x] == "NA"]
 
10
  dayIcols2show = list(dayIcols_settings.keys())#[x for x in dayIdata_columns if not x == db_daycol]
11
 
12
 
 
39
  return None
40
  return html.Div([dcc.Markdown(desc_txt,
41
  dangerously_allow_html=True)])
 
 
42
  # Callback pour gérer l'ouverture et la fermeture de la modale, et l'affichage du graphique
43
  @app.callback(
44
  [Output('evotime-modal-graph-modal', 'is_open'),
 
80
  selected_period, start_date, end_date, time_db, day_db):
81
  if n_clicks is None or n_clicks == 0:
82
  return [go.Figure(), False, "", ""]
 
83
  if (not selected_db or not selected_col or not selected_viz) :
84
+ return [go.Figure(), True, "Sélectionnez dans les menus déroulants", ""]
 
85
  if selected_db == dbTime_name:
86
  df = pd.DataFrame(time_db)
87
  dfcol = db_timecol
 
91
  else:
92
  sys.exit(1)
93
 
94
+ df = df.sort_values(by=dfcol)
95
+
96
  if selected_period == "stat_perso" and (not start_date or not end_date):
97
  return [go.Figure(), True, "Sélectionnez une date de début et fin", ""]
98
 
 
118
  for col in dayI_cols:
119
  df[col] = df[col + "_1"].fillna(0) + df[col + "_2"].fillna(0)
120
 
121
+ #df.to_pickle('df_grapheàchoix_1.pkl')
122
+
123
  if selected_viz == "boxplot" and isinstance(selected_col, list) and len(selected_col) > 1:
124
  df_melted = pd.melt(df, id_vars=[db_daycol], value_vars=selected_col,
125
  var_name='variable', value_name='valeur')
 
154
  )
155
  update_layout_cols(selected_col)
156
  yaxis_layout['title'] = colsettings[selected_col[0]]['lab']
157
+
158
  fig.update_layout(
159
  xaxis=dict(domain=[0.25, 0.75], showline=True, linewidth=2, linecolor='black'),
160
  yaxis=yaxis_layout,
 
232
  if selected_db:
233
  if selected_db == dbTime_name:
234
  columns = [{'label': col, 'value': col} for col in timecols2show]
 
 
235
  elif selected_db == dbDayI_name:
236
  columns = [{'label': col + "=" + dayIcols_settings[col]['lab'],
237
  'value': col} for col in dayI_cols + dayIcols2show]
callbacks/tab_répartFréq_callbacks.py CHANGED
@@ -35,8 +35,6 @@ def register_callbacks(app):
35
  def update_analyse_pie_chart(n_clicks, selected_period, selected_L,
36
  start_date, end_date, time_db):
37
 
38
- print("je vais faire le pie chart")
39
-
40
  if n_clicks is None or n_clicks == 0:
41
  return [""] * 5 + [False, ""]
42
 
@@ -44,6 +42,8 @@ def register_callbacks(app):
44
  return [""] * 5 + [True, "Sélectionnez une période"]
45
 
46
  df = pd.DataFrame(time_db)
 
 
47
 
48
  if selected_period != 'stat_perso':
49
  start_date, end_date = get_startrange_date_vLatest(df[db_timecol], selected_period)
@@ -123,9 +123,6 @@ def register_callbacks(app):
123
  }),
124
  period_subtit,
125
  pie_chart_tit,
126
- # dcc.Graph(figure=fig_barplot,config= {
127
- # 'scrollZoom': True # Activer le zoom avec la molette
128
- # }),
129
  False, ""]
130
 
131
 
@@ -170,11 +167,6 @@ def register_callbacks(app):
170
 
171
  date_info = f"Zoom sur les données du {start_date} au {end_date}"
172
 
173
- # conn = sqlite3.connect(db_file)
174
- # df = pd.read_sql_query(query, conn)
175
- # conn.close()
176
-
177
-
178
  if selected_db == dbTime_name:
179
  xcol = db_timecol
180
  else:
@@ -182,6 +174,9 @@ def register_callbacks(app):
182
  if selected_db == dbDayI_name:
183
  for col in dayI_cols:
184
  df[col] = df[col + "_1"].fillna(0) + df[col + "_2"].fillna(0)
 
 
 
185
  # xt fin discriminer Fréquence du réseau ou de la génératrice.
186
  # Les 2 sources peuvent être disciminée par leurs valeur:
187
  # Le réseau à une fréquence très stable <49,5Hz-50,5Hz>.
@@ -302,219 +297,12 @@ def register_callbacks(app):
302
  div_container.append(dcc.Markdown(get_plotdesc(col1, col2),
303
  dangerously_allow_html=True))
304
 
305
- # ###** graphe 5 : XT Fin - b) valeurs journalières
306
- #
307
- # df['day'] = pd.to_datetime(df[db_timecol]).dt.date
308
- # #### Barplot idem précédent mais par jour
309
- # agg_df = df.groupby(['day', 'source']).size()
310
- # wagg_df = agg_df.unstack(fill_value=0)
311
- # pct_df = wagg_df.div(wagg_df.sum(axis=1), axis=0) * 100
312
- #
313
- # figBarDay = make_subplots(rows=2, cols=1, vertical_spacing=0.04,
314
- # shared_xaxes=True)
315
- #
316
- # max_mean_col = pct_df.mean().idxmax()
317
- #
318
- # # S'il n'y a qu'un type -> np.min ne va pas marcher
319
- # cut_int = [10, np.min(pct_df[max_mean_col]) - 0.5]
320
- # # Pour assurer qu'elle soit tracée en premier
321
- # othercols = [x for x in colors.keys() if x != max_mean_col]
322
- #
323
- # # Traces pour les deux graphes
324
- # for source in [max_mean_col] + othercols:
325
- # if source in pct_df.columns:
326
- # figBarDay.add_trace(go.Bar(
327
- # x=pct_df.index,
328
- # y=pct_df[source],
329
- # name=source,
330
- # marker_color=colors[source],
331
- # showlegend=False
332
- # ), row=2, col=1)
333
- # figBarDay.add_trace(go.Bar(
334
- # x=pct_df.index,
335
- # y=pct_df[source],
336
- # name=source,
337
- # marker_color=colors[source],
338
- # showlegend=True
339
- # ), row=1, col=1)
340
- #
341
- # figBarDay.update_layout(
342
- # title='<b>Répartition des sources par jour</b>',
343
- # xaxis=dict(title='Jour'),
344
- # barmode='stack',
345
- # legend_title='Source',
346
- # hovermode='x unified'
347
- # )
348
- # figBarDay.update_yaxes(range=[cut_int[1], 105], row=1, col=1)
349
- # figBarDay.update_xaxes(visible=False, row=1, col=1,
350
- # range=[start_date, end_date]
351
- # )
352
- # figBarDay.update_yaxes(range=[0, cut_int[0]], row=2, col=1)
353
- #
354
- # # Ajouter les annotations au-dessus de chaque barre
355
- # annotations = []
356
- #
357
- # # Parcourir chaque jour pour ajouter l'annotation correspondante
358
- # for idx, day in enumerate(pct_df.index):
359
- # # Récupérer les pourcentages pour chaque source ce jour-là
360
- # percentages = pct_df.loc[day]
361
- # # Trier les sources pour correspondre à l'ordre des couleurs si nécessaire
362
- # sources_in_day = [source for source in [max_mean_col] + othercols if source in percentages.index]
363
- # # Formater les pourcentages en chaîne de caractères
364
- # pct_strings = [f"{percentages[source]:.1f}%" for source in sources_in_day]
365
- # # Joindre les pourcentages avec "/"
366
- # annotation_text = "/".join(pct_strings)
367
- # # Ajouter l'annotation au-dessus de la barre (ligne 1)
368
- # annotations.append(dict(
369
- # x=day,
370
- # y=105, # Position en y au-dessus du maximum (ajustez si nécessaire)
371
- # xref='x1', # Référence à l'axe x du subplot en ligne 1
372
- # yref='y1', # Référence à l'axe y du subplot en ligne 1
373
- # text=annotation_text,
374
- # showarrow=False,
375
- # font=dict(color='black', size=14),
376
- # xanchor='center',
377
- # yanchor='bottom'
378
- # ))
379
- #
380
- # # Mettre à jour la mise en page avec les annotations
381
- # figBarDay.update_layout(annotations=annotations)
382
- #
383
- #
384
- # div_container.append(dcc.Graph(id='graph-XT_FinDay', figure=figBarDay,config= {
385
- # 'scrollZoom': True # Activer le zoom avec la molette
386
- # }))
387
- # div_container.append(dcc.Markdown(get_plotdesc(col1, col2),
388
- # dangerously_allow_html=True))
389
- #
390
- # #******************************************3
391
- # #### Barplot idem précédent mais par jour
392
- #
393
- # div_container.append(dcc.Markdown("<h3>Barplot par jour et période</h3>",
394
- # dangerously_allow_html=True))
395
- #
396
- # # Assurez-vous que 'db_timecol' est au format datetime
397
- # dayp_df = df.copy()
398
- # dayp_df[db_timecol] = pd.to_datetime(dayp_df[db_timecol])
399
- #
400
- # # Créer la colonne 'day'
401
- # dayp_df[db_daycol] = dayp_df[db_timecol].dt.date
402
- #
403
- # # Définir une fonction pour étiqueter les périodes
404
- # def label_period(row):
405
- # time = row[db_timecol].time()
406
- # if time >= datetime.strptime("08:00", "%H:%M").time() and time < datetime.strptime("18:00", "%H:%M").time():
407
- # return 'Jour'
408
- # else:
409
- # return 'Nuit'
410
- #
411
- # # Appliquer la fonction pour créer la colonne 'period'
412
- # dayp_df['period'] = dayp_df.apply(label_period, axis=1)
413
- #
414
- # # Créer une période 'Global' en dupliquant les données
415
- # df_global = dayp_df.copy()
416
- # df_global['period'] = 'Global'
417
- #
418
- # # Concaténer les dataframes
419
- # df_all = pd.concat([dayp_df, df_global])
420
- #
421
- # # Grouper par 'day', 'period', 'source' et calculer les comptes
422
- # aggperiod_df = df_all.groupby(['day', 'period', 'source']).size().reset_index(name='count')
423
- #
424
- # # Calculer les comptes totaux par 'day' et 'period'
425
- # total_counts = aggperiod_df.groupby(['day', 'period'])['count'].sum().reset_index(name='total_count')
426
- #
427
- # # Fusionner les comptes totaux avec aggperiod_df
428
- # aggperiod_df = aggperiod_df.merge(total_counts, on=['day', 'period'])
429
- #
430
- # # Calculer les pourcentages
431
- # aggperiod_df['percentage'] = aggperiod_df['count'] / aggperiod_df['total_count'] * 100
432
- #
433
- # # Créer un mapping des jours à des valeurs numériques
434
- # unique_days = sorted(aggperiod_df['day'].unique())
435
- # day_to_num = {day: idx for idx, day in enumerate(unique_days)}
436
- #
437
- # # Ajouter une colonne numérique pour le jour
438
- # aggperiod_df['day_num'] = aggperiod_df['day'].map(day_to_num)
439
- #
440
- # # Définir la largeur des barres et les offsets pour les périodes
441
- # bar_width = 0.2 # Ajustez cette valeur selon vos préférences
442
- # period_offsets = {'Global': -bar_width, 'Jour': 0, 'Nuit': bar_width}
443
- #
444
- # # Calculer les positions x pour chaque barre
445
- # aggperiod_df['x'] = aggperiod_df['day_num'] + aggperiod_df['period'].map(period_offsets)
446
- #
447
- # # Créer la figure
448
- # figBarDayPeriod = go.Figure()
449
- #
450
- # # Liste des périodes et des sources uniques
451
- # periods = ['Global', 'Jour', 'Nuit']
452
- # sources = aggperiod_df['source'].unique()
453
- #
454
- # # Initialiser un ensemble pour suivre les sources déjà ajoutées à la légende
455
- # legend_added = set()
456
- #
457
- # # Ajouter des traces pour chaque source et chaque période
458
- # for day_num in aggperiod_df['day_num'].unique():
459
- # day_str = str(day_num) # Convertir le numéro du jour en chaîne pour l'utiliser dans alignmentgroup
460
- # for period in periods:
461
- # for source in sources:
462
- # df_plot = aggperiod_df[
463
- # (aggperiod_df['day_num'] == day_num) &
464
- # (aggperiod_df['period'] == period) &
465
- # (aggperiod_df['source'] == source)]
466
- # if not df_plot.empty:
467
- # figBarDay.add_trace(go.Bar(
468
- # x=df_plot['x'],
469
- # y=df_plot['percentage'],
470
- # name=source,
471
- # marker_color=colors.get(source, 'grey'),
472
- # legendgroup=source,
473
- # showlegend=(source not in legend_added),
474
- # offsetgroup=period,
475
- # alignmentgroup='day_' + day_str, # Utiliser une chaîne unique pour chaque jour
476
- # width=bar_width,
477
- # customdata=df_plot[['day', 'period']],
478
- # hovertemplate='Jour: %{customdata[0]}<br>Période: %{customdata[1]}<br>Source: %{name}<br>Pourcentage: %{y:.1f}%<extra></extra>'
479
- # ))
480
- # legend_added.add(source)
481
- # # Mettre à jour la mise en page pour regrouper les barres par jour et par période
482
- # figBarDayPeriod.update_layout(
483
- # title='<b>Répartition des sources par jour et par période</b>',
484
- # xaxis_title='Jour',
485
- # yaxis_title='Pourcentage',
486
- # barmode='stack',
487
- # bargap=0.05, # Ajuster pour contrôler l'espacement entre les barres d'un même groupe
488
- # bargroupgap=0.15, # Ajuster pour contrôler l'espacement entre les groupes de jours
489
- # legend_title='Source',
490
- # hovermode='x unified'
491
- # )
492
- #
493
- # # Configurer les ticks de l'axe x pour afficher les dates
494
- # day_positions = [day_to_num[day] for day in unique_days]
495
- # day_labels = [str(day) for day in unique_days]
496
- #
497
- # figBarDayPeriod.update_xaxes(
498
- # tickmode='array',
499
- # tickvals=day_positions,
500
- # ticktext=day_labels,
501
- # tickangle=45 # Pivoter les labels si nécessaire
502
- # )
503
- #
504
- # # Ajuster la plage de l'axe x pour inclure toutes les barres
505
- # figBarDayPeriod.update_xaxes(range=[min(day_positions) - 0.5, max(day_positions) + 0.5])
506
- # # Afficher la figure
507
- # div_container.append(dcc.Graph(id='graph-XT_FinDayPeriode', figure=figBarDayPeriod,config= {
508
- # 'scrollZoom': True # Activer le zoom avec la molette
509
- # }))
510
- # div_container.append(dcc.Markdown(get_plotdesc(col1, col2),
511
- # dangerously_allow_html=True))
512
 
513
  ###** graphe 5 : XT Fin - b) valeurs journalières
514
 
515
  df['day'] = pd.to_datetime(df[db_timecol]).dt.date
516
  #### Barplot idem précédent mais par jour
517
- agg_df = df.groupby(['day', 'source']).size()
518
  wagg_df = agg_df.unstack(fill_value=0)
519
  pct_df = wagg_df.div(wagg_df.sum(axis=1), axis=0) * 100
520
 
@@ -819,12 +607,8 @@ def register_callbacks(app):
819
  ))
820
 
821
  #### ajouter les variables I
822
- # selected_db = dbDayI_name
823
- # queryI = get_query_extractInterval(selected_db, start_date, end_date)
824
- # conn = sqlite3.connect(db_file)
825
- # dayI_df = pd.read_sql_query(queryI, conn)
826
- # conn.close()
827
  dayI_df = pd.DataFrame(day_db)
 
828
 
829
  if selected_period != 'stat_perso':
830
  start_date, end_date = get_startrange_date_vLatest(dayI_df[db_daycol], selected_period)
 
35
  def update_analyse_pie_chart(n_clicks, selected_period, selected_L,
36
  start_date, end_date, time_db):
37
 
 
 
38
  if n_clicks is None or n_clicks == 0:
39
  return [""] * 5 + [False, ""]
40
 
 
42
  return [""] * 5 + [True, "Sélectionnez une période"]
43
 
44
  df = pd.DataFrame(time_db)
45
+ df = df.sort_values(by=db_timecol)
46
+
47
 
48
  if selected_period != 'stat_perso':
49
  start_date, end_date = get_startrange_date_vLatest(df[db_timecol], selected_period)
 
123
  }),
124
  period_subtit,
125
  pie_chart_tit,
 
 
 
126
  False, ""]
127
 
128
 
 
167
 
168
  date_info = f"Zoom sur les données du {start_date} au {end_date}"
169
 
 
 
 
 
 
170
  if selected_db == dbTime_name:
171
  xcol = db_timecol
172
  else:
 
174
  if selected_db == dbDayI_name:
175
  for col in dayI_cols:
176
  df[col] = df[col + "_1"].fillna(0) + df[col + "_2"].fillna(0)
177
+
178
+ df = df.sort_values(by=xcol)
179
+
180
  # xt fin discriminer Fréquence du réseau ou de la génératrice.
181
  # Les 2 sources peuvent être disciminée par leurs valeur:
182
  # Le réseau à une fréquence très stable <49,5Hz-50,5Hz>.
 
297
  div_container.append(dcc.Markdown(get_plotdesc(col1, col2),
298
  dangerously_allow_html=True))
299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
301
  ###** graphe 5 : XT Fin - b) valeurs journalières
302
 
303
  df['day'] = pd.to_datetime(df[db_timecol]).dt.date
304
  #### Barplot idem précédent mais par jour
305
+ agg_df = df.groupby([db_daycol, 'source']).size()
306
  wagg_df = agg_df.unstack(fill_value=0)
307
  pct_df = wagg_df.div(wagg_df.sum(axis=1), axis=0) * 100
308
 
 
607
  ))
608
 
609
  #### ajouter les variables I
 
 
 
 
 
610
  dayI_df = pd.DataFrame(day_db)
611
+ dayI_df = dayI_df.sort_values(by=db_daycol)
612
 
613
  if selected_period != 'stat_perso':
614
  start_date, end_date = get_startrange_date_vLatest(dayI_df[db_daycol], selected_period)
data_processing_v3.py CHANGED
@@ -1,7 +1,7 @@
1
  import pandas as pd
2
  import re
3
  from settings import *
4
- # from utils_fcts import print_df_shape
5
 
6
  def clean_cols(myl):
7
  # myl = [re.sub(r'\[.*\]', '', x) for x in myl]
@@ -106,8 +106,16 @@ def file2tables(file_path):
106
  ###############################################################
107
  time_data = pd.DataFrame(time_lines)#, columns=new_columns)
108
 
 
109
  time_data.loc[:, 0] = pd.to_datetime(time_data.iloc[:, 0],
110
  format='%d.%m.%Y %H:%M').dt.strftime('%Y-%m-%d %H:%M:%S')
 
 
 
 
 
 
 
111
  ntime, ncols = time_data.shape
112
  time_data.columns = new_columns
113
 
@@ -174,6 +182,11 @@ def file2tables(file_path):
174
  dayI_data = dayI_data[1:]
175
  dayI_data.insert(0, day_txt_cols[0], date_day)
176
 
 
 
 
 
 
177
  ndayI, ndayIcols = dayI_data.shape
178
 
179
  assert ndayI <= 1
 
1
  import pandas as pd
2
  import re
3
  from settings import *
4
+ # from utils_fcts import print_df_shape # laisser commenté : importé dans utils_fcts ; erreru import circulaire
5
 
6
  def clean_cols(myl):
7
  # myl = [re.sub(r'\[.*\]', '', x) for x in myl]
 
106
  ###############################################################
107
  time_data = pd.DataFrame(time_lines)#, columns=new_columns)
108
 
109
+ # la 1ère colonne en datetime
110
  time_data.loc[:, 0] = pd.to_datetime(time_data.iloc[:, 0],
111
  format='%d.%m.%Y %H:%M').dt.strftime('%Y-%m-%d %H:%M:%S')
112
+
113
+ # Conversion des autres colonnes en numérique (float)
114
+ for col in range(1, time_data.shape[1]):
115
+ time_data.iloc[:, col] = pd.to_numeric(time_data.iloc[:, col], errors='coerce')
116
+
117
+ #time_data.to_pickle('time_data_v3.pkl')
118
+
119
  ntime, ncols = time_data.shape
120
  time_data.columns = new_columns
121
 
 
182
  dayI_data = dayI_data[1:]
183
  dayI_data.insert(0, day_txt_cols[0], date_day)
184
 
185
+ # Conversion des autres colonnes en numérique (float)
186
+ for col in range(1, dayI_data.shape[1]):
187
+ dayI_data.iloc[:, col] = pd.to_numeric(dayI_data.iloc[:, col], errors='coerce')
188
+
189
+
190
  ndayI, ndayIcols = dayI_data.shape
191
 
192
  assert ndayI <= 1
settings.py CHANGED
@@ -554,7 +554,7 @@ showcols_settings = {
554
 
555
  for icol in time_added_cols:
556
  if not icol in showcols_settings:
557
- showcols_settings[icol] = showcols_settings[icol.replace('_L1_L2', '_L1')]
558
  showcols_settings[icol]['lab'] =showcols_settings[icol]['lab'].replace("L1", "L1+L2")
559
  showcols_settings[icol]['description'] =showcols_settings[icol]['description'].replace("L1", "L1+L2")
560
 
 
554
 
555
  for icol in time_added_cols:
556
  if not icol in showcols_settings:
557
+ showcols_settings[icol] = showcols_settings[icol.replace('_L1_L2', '_L1')].copy()
558
  showcols_settings[icol]['lab'] =showcols_settings[icol]['lab'].replace("L1", "L1+L2")
559
  showcols_settings[icol]['description'] =showcols_settings[icol]['description'].replace("L1", "L1+L2")
560