def change_ventana_tiempo(fecha_ini, tipo_sensor): if fecha_ini == None: fecha_ini = datos.fecha_inicial(tipo_sensor, 'x') fecha_ini = str(fecha_ini) fecha_ini = dt.strptime( str( dt(int(fecha_ini[0:4]), int(fecha_ini[5:7]), int(fecha_ini[8:10]), 0, 0, 0)), '%Y-%m-%d %H:%M:%S') fecha_fin = datos.fecha_final(tipo_sensor, 'x') rango = datos.dias_entre_fechas(fecha_ini, fecha_fin) if rango > 13: return [{ "label": key, "value": value } for key, value in datos.ventana_tiempo(3).items() ], str(list(datos.ventana_tiempo(3).values())[0]) elif rango > 6 and rango < 14: return [{ "label": key, "value": value } for key, value in datos.ventana_tiempo(2).items() ], str(list(datos.ventana_tiempo(3).values())[0]) elif rango > 0 and rango < 7: return [{ "label": key, "value": value } for key, value in datos.ventana_tiempo(1).items() ], str(list(datos.ventana_tiempo(3).values())[0]) elif rango == 0: return [{ "label": key, "value": value } for key, value in datos.ventana_tiempo(0).items() ], str(list(datos.ventana_tiempo(3).values())[0])
def update_grafico_2(n_clicks, cantidad_sensores, hora, tipo_sensor, sensor, sensor_multi, fecha, ventana_tiempo, ejes, eje): if len(ejes) < 1: ejes.append('x') if fecha != None: if str(str(fecha).split(sep='T')[0]) == str( str(datos.fecha_inicial(tipo_sensor, eje)).split(sep=' ')[0]): #fecha = dt.strptime(str(str(fecha).split(sep='T')[0]) + ' ' + str(str(datos.fecha_inicial()).split(sep=' ')[1]),'%Y-%m-%d %H:%M:%S') fecha = dt.strptime( str(str(fecha).split(sep='T')[0]) + ' ' + datos.crear_hora(hora), '%Y-%m-%d %H:%M:%S') else: fecha = dt.strptime( str(str(fecha).split(sep='T')[0]) + ' ' + datos.crear_hora(hora), '%Y-%m-%d %H:%M:%S') else: fecha = datos.fecha_inicial(tipo_sensor, eje) #Se inicializan variables df = pd.DataFrame() fig_2 = go.Figure() if n_clicks >= 0: fecha_ini_titulo, fecha_fin_titulo = datos.fecha_titulo( fecha, ventana_tiempo) #Dependiendo del tipo de sensor se crean visualizaciones distintas if tipo_sensor == 'weather-station': #Aqui se crea el histograma circular que contine datos de la direccion y velocidad del viento dir = datos.datos_ace(dt(2008, 4, 1, 0, 38, 3), ventana_tiempo, 'dir_viento')['dir_viento'].tolist() vel = datos.datos_ace(dt(2008, 4, 1, 0, 38, 3), ventana_tiempo, 'vel_viento')['vel_viento'].tolist() tmp1 = collections.Counter(dir) ini, fin = datos.rangos(tmp1) rr, tt = datos.datos_por_rango( pd.DataFrame({ 'dir_viento': dir, 'vel_viento': vel }), ini, fin) dff = pd.DataFrame({'Dirección': tt, 'Velocidad (m/s)': rr}) fig_2 = px.bar_polar( dff, r="Velocidad (m/s)", theta="Dirección", color_discrete_sequence=px.colors.sequential.Plasma_r) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_2.update_layout( title={ 'text': "Dirección y Velocidad (m/s) del viento durante " + str(titulo_OHLC) + " " }) elif tipo_sensor == 'Acelerometro': if cantidad_sensores == '1-sensor': # La variable df contiene el dataframe que se utiliza para generar el histograma # Aqui se crea el histograma trace_sec2 = [] colors = ['#e6194b', '#3cb44b', '#ffe119'] count = 0 for e in ejes: start_time = time() df = datos.datos_ace(fecha, ventana_tiempo, sensor, e) start_time = time() #fig_2 = go.Figure(data=[go.Histogram(x=df[sensor],showlegend=False)]) trace_sec2.append( go.Histogram(x=df[sensor], showlegend=True, marker_color=colors[count], name=datos.traductor_nombre(sensor) + ' eje: ' + str(e))) count = count + 1 fig_2 = go.Figure(data=trace_sec2) elapsed_time = time() - start_time print( "Tiempo Transcurrido crear Histograma: %0.1f seconds." % elapsed_time) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_2.update_layout( title="Frecuencia de datos cada " + str(datos.titulo_freq_datos(ventana_tiempo)) + " del " + str(datos.traductor_nombre(sensor)) + "<br>durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")", yaxis={"title": "Frecuencia (N° de Datos)"}, xaxis={"title": "Aceleración (cm/s²)"}, bargap=0.1, ) else: #Listas que conteneran cada trace generado por cada dataframe creado para poder visualizarlos en una grafica trace_sec2 = [] #colores para las graficas colors = [ '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#ffffff', '#000000' ] count = 0 #por cada sensor seleccionado se crean df for sen in sensor_multi: df = datos.datos_ace(fecha, ventana_tiempo, sen, eje) # Aqui se crea el histograma trace_sec2.append( go.Histogram(x=df[sen], showlegend=True, marker_color=colors[count], name=datos.traductor_nombre(sen))) count = count + 1 fig_2 = go.Figure(data=trace_sec2) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_2.update_layout( title="Frecuencia de datos cada " + str(datos.titulo_freq_datos(ventana_tiempo)) + "<br>durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")", yaxis={"title": "Frecuencia (N° de Datos)"}, xaxis={"title": "Aceleración (cm/s²)"}, bargap=0.1, ) return fig_2
def update_grafico_1(n_clicks, cantidad_sensores, hora, tipo_sensor, sensor, sensor_multi, fecha, ventana_tiempo, ejes, eje): if len(ejes) < 1: ejes.append('x') if fecha != None: if str(str(fecha).split(sep='T')[0]) == str( str(datos.fecha_inicial(tipo_sensor, eje)).split(sep=' ')[0]): #fecha = dt.strptime(str(str(fecha).split(sep='T')[0]) + ' ' + str(str(datos.fecha_inicial()).split(sep=' ')[1]),'%Y-%m-%d %H:%M:%S') fecha = dt.strptime( str(str(fecha).split(sep='T')[0]) + ' ' + datos.crear_hora(hora), '%Y-%m-%d %H:%M:%S') else: fecha = dt.strptime( str(str(fecha).split(sep='T')[0]) + ' ' + datos.crear_hora(hora), '%Y-%m-%d %H:%M:%S') else: fecha = datos.fecha_inicial(tipo_sensor, eje) #Se inicializan variables df = pd.DataFrame() fig_1 = go.Figure() if n_clicks >= 0: fecha_ini_titulo, fecha_fin_titulo = datos.fecha_titulo( fecha, ventana_tiempo) #Dependiendo del tipo de sensor se crean visualizaciones distintas if tipo_sensor == 'Acelerometro': if cantidad_sensores == '1-sensor': #Aqui se crea el grafico boxplot start_time = time() repeat = 12 #Cuando la ventana de tiempo es de 1 hora o 1 dia se obtinen 12 box en cambio si es de 7 dias o 14 se obtienen 14 por eso cambia el valor de repeat if ventana_tiempo == '12S' or ventana_tiempo == '288S': repeat = 12 else: repeat = 14 # bucle que genera cada box for e in ejes: for i in range(repeat): if i == 0: vars()['df' + str(i)], vars()['ultimo' + str(i)] = datos.datos_box( fecha, ventana_tiempo, sensor, e) fig_1.add_trace( go.Box(y=vars()['df' + str(i)][str( vars()['ultimo' + str(i)])], name=str(vars()['ultimo' + str(i)]) + ' eje: ' + str(e), boxpoints='suspectedoutliers', showlegend=False)) else: vars()['df' + str(i)], vars()['ultimo' + str(i)] = datos.datos_box( vars()['ultimo' + str(i - 1)], ventana_tiempo, sensor, e) fig_1.add_trace( go.Box(y=vars()['df' + str(i)][str( vars()['ultimo' + str(i)])], name=str(vars()['ultimo' + str(i)]) + ' eje: ' + str(e), boxpoints='suspectedoutliers', showlegend=False)) elapsed_time = time() - start_time print("Tiempo Transcurrido crear BOX: %0.1f seconds." % elapsed_time) # Titulos para el grafico OHLC y Boxplot titulo_box = datos.titulo_box(ventana_tiempo) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_1.update_layout( title="Promedio de datos cada " + str(titulo_box) + " del " + str(datos.traductor_nombre(sensor)) + " durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")", yaxis={"title": "Aceleración (cm/s²)"}) else: #Listas que conteneran cada trace generado por cada dataframe creado para poder visualizarlos en una grafica trace_sec1 = [] #Para el grafico boxplot repeat = 12 #Cuando la ventana de tiempo es de 1 hora o 1 dia se obtinen 12 box en cambio si es de 7 dias o 14 se obtienen 14 por eso cambia el valor de repeat if ventana_tiempo == '12S' or ventana_tiempo == '288S': repeat = 12 else: repeat = 14 #colores para las graficas colors = [ '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#ffffff', '#000000' ] count = 0 #por cada sensor seleccionado se crean df for sen in sensor_multi: # bucle que genera cada box para guardarlo en el trace for i in range(repeat): if i == 0: vars()['df' + str(i)], vars()['ultimo' + str(i)] = datos.datos_box( fecha, ventana_tiempo, sen, eje) trace_sec1.append( go.Box(y=vars()['df' + str(i)][str( vars()['ultimo' + str(i)])], name=str(vars()['ultimo' + str(i)]), boxpoints='suspectedoutliers', showlegend=False, marker_color=colors[count])) else: vars()['df' + str(i)], vars()['ultimo' + str(i)] = datos.datos_box( vars()['ultimo' + str(i - 1)], ventana_tiempo, sen, eje) trace_sec1.append( go.Box(y=vars()['df' + str(i)][str( vars()['ultimo' + str(i)])], name=str(vars()['ultimo' + str(i)]), boxpoints='suspectedoutliers', showlegend=False, marker_color=colors[count])) count = count + 1 fig_1 = go.Figure(data=trace_sec1) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) titulo_box = datos.titulo_box(ventana_tiempo) fig_1.update_layout( title="Promedio de datos cada " + str(titulo_box) + ", durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")", yaxis={"title": "Aceleración (cm/s²)"}) elif tipo_sensor == 'weather-station': # La variable df contiene el dataframe que se utiliza para generar el graficos OHLC df = datos.datos_ace(dt(2008, 4, 1, 0, 38, 3), ventana_tiempo, 'humedad') # Aqui se crea el grafico OHLC para la humedad fig_1.add_trace( go.Ohlc(x=df['fecha'], open=df['open'], high=df['max'], low=df['min'], close=df['close'], increasing_line_color='blue', decreasing_line_color='red', showlegend=True, name='Humedad')) fig_1.update(layout_xaxis_rangeslider_visible=False) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) #titulos para ambos graficos OHLC fig_1.update_layout(title={ 'text': "Datos cada " + str(datos.titulo_freq_datos(ventana_tiempo)) + " de la Humedad durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")" }, yaxis={"title": "Humedad"}) return fig_1
def update_grafico_principal(n_clicks, click_linea_sup, click_linea_inf, cantidad_sensores, hora, tipo_sensor, sensor, sensor_multi, fecha, ventana_tiempo, linea_control_sup, linea_control_inf, ejes, eje): if len(ejes) < 1: ejes.append('x') if fecha != None: if str(str(fecha).split(sep='T')[0]) == str( str(datos.fecha_inicial(tipo_sensor, eje)).split(sep=' ')[0]): #fecha = dt.strptime(str(str(fecha).split(sep='T')[0]) + ' ' + str(str(datos.fecha_inicial()).split(sep=' ')[1]),'%Y-%m-%d %H:%M:%S') fecha = dt.strptime( str(str(fecha).split(sep='T')[0]) + ' ' + datos.crear_hora(hora), '%Y-%m-%d %H:%M:%S') else: fecha = dt.strptime( str(str(fecha).split(sep='T')[0]) + ' ' + datos.crear_hora(hora), '%Y-%m-%d %H:%M:%S') else: fecha = datos.fecha_inicial(tipo_sensor, eje) #Se inicializan variables df = pd.DataFrame() fig_principal = go.Figure() alert_inf, alert_sup, fecha_peak_sup, fecha_peak_inf = '---', '---', '---', '---' promedio, maximo, minimo, count_max, count_min, fecha_ultimo_max, fecha_ultimo_min = '---', '---', '---', '---', '---', '---', '---' #Listas que conteneran cada trace generado por cada dataframe creado para poder visualizarlos en una grafica trace_principal = [] if n_clicks >= 0: fecha_ini_titulo, fecha_fin_titulo = datos.fecha_titulo( fecha, ventana_tiempo) #Dependiendo del tipo de sensor se crean visualizaciones distintas if tipo_sensor == 'Acelerometro': if cantidad_sensores == '1-sensor': # La variable df contiene el dataframe que se utiliza para generar los graficos OHLC e histograma new_df = pd.DataFrame() list_df = [] colors = [ '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4' ] count = 0 new_count_de = 0 new_count_in = 1 for e in ejes: start_time = time() df = datos.datos_ace(fecha, ventana_tiempo, sensor, e) elapsed_time = time() - start_time print("Tiempo Transcurrido crear DF: %0.1f seconds." % elapsed_time) # Aqui se crea el grafico OHLC start_time = time() trace_principal.append( go.Ohlc(x=df['fecha'], open=df['open'], high=df['max'], low=df['min'], close=df['close'], increasing_line_color=colors[new_count_in], decreasing_line_color=colors[new_count_de], name=str( datos.traductor_nombre(sensor) + ' eje: ' + str(e)), showlegend=True)) count = count + 1 new_count_in = new_count_in + 2 new_count_de = new_count_de + 2 new_df = df #lista de dataframe para generar los indicadores resumen list_df.append(df) #Variables que contienen los datos a mostrar en los indicadores de promedio, minimo y maximo promedio, maximo, minimo, count_max, count_min, fecha_ultimo_max, fecha_ultimo_min = datos.datos_mini_container( new_df, sensor) df = pd.concat(list_df, axis=0, ignore_index=True) fig_principal = go.Figure(data=trace_principal) #Aqui se agregan las lineas de control if (click_linea_inf > 0 and linea_control_inf != None) and ( click_linea_sup > 0 and linea_control_sup != None): trace_linea_inf, alert_inf, fecha_peak_inf = datos.lineas_control( 'inf', df, linea_control_inf, 0) trace_linea_sup, alert_sup, fecha_peak_sup = datos.lineas_control( 'sup', df, 0, linea_control_sup) trace_linea_inf.extend(trace_linea_sup) trace_principal.extend(trace_linea_inf) fig_principal = go.Figure(data=trace_principal) #Linea de control inferior elif click_linea_inf > 0 and linea_control_inf != None: trace_linea_inf, alert_inf, fecha_peak_inf = datos.lineas_control( 'inf', df, linea_control_inf, 0) trace_principal.extend(trace_linea_inf) fig_principal = go.Figure(data=trace_principal) #Linea de control superior elif click_linea_sup > 0 and linea_control_sup != None: trace_linea_sup, alert_sup, fecha_peak_sup = datos.lineas_control( 'sup', df, 0, linea_control_sup) trace_principal.extend(trace_linea_sup) fig_principal = go.Figure(data=trace_principal) fig_principal.update(layout_xaxis_rangeslider_visible=False) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_principal.update_layout( title={ 'text': "Datos cada " + str(datos.titulo_freq_datos(ventana_tiempo)) + " del " + str(datos.traductor_nombre(sensor)) + " durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")" }, yaxis={"title": "Aceleración (cm/s²)"}) elapsed_time = time() - start_time print("Tiempo Transcurrido crear OHLC: %0.1f seconds." % elapsed_time) else: #colores para las graficas colors = [ '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#ffffff', '#000000', '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#ffffff', '#000000' ] count = 0 new_count_de = 0 new_count_in = 1 new_df = pd.DataFrame() new_sensor = '' list_df = [] #por cada sensor seleccionado se crean df for sen in sensor_multi: df = datos.datos_ace(fecha, ventana_tiempo, sen, eje) #trace para el grafico OHLC trace_principal.append( go.Ohlc(x=df['fecha'], open=df['open'], high=df['max'], low=df['min'], close=df['close'], increasing_line_color=colors[new_count_in], decreasing_line_color=colors[new_count_de], showlegend=True, name=datos.traductor_nombre(sen))) count = count + 1 new_count_in = new_count_in + 2 new_count_de = new_count_de + 2 new_df = df new_sensor = sen #lista de dataframe para generar los indicadores resumen list_df.append(df) #Variables que contienen los datos a mostrar en los indicadores de promedio, minimo y maximo promedio, maximo, minimo, count_max, count_min, fecha_ultimo_max, fecha_ultimo_min = datos.datos_mini_container( new_df, new_sensor) df = pd.concat(list_df, axis=0, ignore_index=True) fig_principal = go.Figure(data=trace_principal) #Aqui se agregan las lineas de control if (click_linea_inf > 0 and linea_control_inf != None) and ( click_linea_sup > 0 and linea_control_sup != None): trace_linea_inf, alert_inf, fecha_peak_inf = datos.lineas_control( 'inf', df, linea_control_inf, 0) trace_linea_sup, alert_sup, fecha_peak_sup = datos.lineas_control( 'sup', df, 0, linea_control_sup) trace_linea_inf.extend(trace_linea_sup) trace_principal.extend(trace_linea_inf) fig_principal = go.Figure(data=trace_principal) #Linea de control inferior elif click_linea_inf > 0 and linea_control_inf != None: trace_linea_inf, alert_inf, fecha_peak_inf = datos.lineas_control( 'inf', df, linea_control_inf, 0) trace_principal.extend(trace_linea_inf) fig_principal = go.Figure(data=trace_principal) #Linea de control superior elif click_linea_sup > 0 and linea_control_sup != None: trace_linea_sup, alert_sup, fecha_peak_sup = datos.lineas_control( 'sup', df, 0, linea_control_sup) trace_principal.extend(trace_linea_sup) fig_principal = go.Figure(data=trace_principal) fig_principal.update(layout_xaxis_rangeslider_visible=False) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_principal.update_layout( title={ 'text': "Datos cada " + str(datos.titulo_freq_datos(ventana_tiempo)) + ", durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")" }, yaxis={"title": "Aceleración (cm/s²)"}) elif tipo_sensor == 'weather-station': # La variable df y dff contiene el dataframe que se utiliza para generar el graficos OHLC df = datos.datos_ace(fecha, ventana_tiempo, 'temperatura') # Aqui se crea el grafico OHLC para la temperatura trace_principal.append( go.Ohlc(x=df['fecha'], open=df['open'], high=df['max'], low=df['min'], close=df['close'], increasing_line_color='green', decreasing_line_color='red', showlegend=True, name='Temperatura')) fig_principal = go.Figure(data=trace_principal) #Aqui se agregan las lineas de control if (click_linea_inf > 0 and linea_control_inf != None) and ( click_linea_sup > 0 and linea_control_sup != None): trace_linea_inf, alert_inf, fecha_peak_inf = datos.lineas_control( 'inf', df, linea_control_inf, 0) trace_linea_sup, alert_sup, fecha_peak_sup = datos.lineas_control( 'sup', df, 0, linea_control_sup) trace_linea_inf.extend(trace_linea_sup) trace_principal.extend(trace_linea_inf) fig_principal = go.Figure(data=trace_principal) #Linea de control inferior elif click_linea_inf > 0 and linea_control_inf != None: trace_linea_inf, alert_inf, fecha_peak_inf = datos.lineas_control( 'inf', df, linea_control_inf, 0) trace_principal.extend(trace_linea_inf) fig_principal = go.Figure(data=trace_principal) #Linea de control superior elif click_linea_sup > 0 and linea_control_sup != None: trace_linea_sup, alert_sup, fecha_peak_sup = datos.lineas_control( 'sup', df, 0, linea_control_sup) trace_principal.extend(trace_linea_sup) fig_principal = go.Figure(data=trace_principal) fig_principal.update(layout_xaxis_rangeslider_visible=False) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) #titulos para ambos graficos OHLC fig_principal.update_layout(title={ 'text': "Datos cada " + str(datos.titulo_freq_datos(ventana_tiempo)) + " de la Temperatura durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")" }, yaxis={"title": "Temperatura (°C)"}) #Se obtienen los datos de los indicadores resumen, en este caso pertenecientes a los datos de temperatura promedio, maximo, minimo, count_max, count_min, fecha_ultimo_max, fecha_ultimo_min = datos.datos_mini_container( df, 'temperatura') return promedio, maximo, minimo, fecha_ultimo_max, fecha_ultimo_min, count_max, count_min, alert_sup, alert_inf, fecha_peak_sup, fecha_peak_inf, fig_principal
def update_fecha(tipo_sensor): ini = datos.fecha_inicial(tipo_sensor, 'x') fin = datos.fecha_final(tipo_sensor, 'x') return ini, fin, ini, ini
dcc.Loading( id="carga-elegir-fecha", children=[ dcc.DatePickerSingle( id='elegir-fecha', display_format='DD/MM/YYYY', min_date_allowed=datos. fecha_inicial( 'Acelerometro', 'x'), max_date_allowed=datos. fecha_final( 'Acelerometro', 'x'), initial_visible_month=datos .fecha_inicial( 'Acelerometro', 'x'), date=datos.fecha_inicial( 'Acelerometro', 'x')), ], type="default") ], style={'textAlign': 'center'}), html.Br(), html.P("Seleccione Ventana de Tiempo", className="control_label", style={ 'textAlign': 'center', 'font-size': '20px' }), html.Div([ dcc.Loading( id="carga-ventana-tiempo", children=[