How to use show_limits method in tempest

Best Python code snippet using tempest_python

op90_plat_comp.py

Source:op90_plat_comp.py Github

copy

Full Screen

1import streamlit as st2import pandas as pd3import numpy as np4import csv5import os6import psycopg27import matplotlib.pyplot as plt8import seaborn as sns9import plotly.express as px10import datetime11from pandas.tseries.offsets import DateOffset1213# Funcitons and constants-------------------------------------------------------------------------------------------------------------------14def connect_db_sql(database="Morganton", user= "postgres", password= "United2018", host="localhost", port="5432"):15 conn = psycopg2.connect(database= database, user=user, password=password, host=host, port=port)16 return conn1718def get_db_sql(conn, query='select * from "hlt_op090_from_200_210"'):19 df = pd.read_sql_query(query,con=conn, parse_dates=['date_time'])20 df.index = pd.to_datetime(df.date_time.dt.date)21 return df2223@st.cache(allow_output_mutation=True)24def long_running_function_to_load_data(query = 'select * from "hlt_op090_from_200_210"'):25 hours = range(0,24)26 shits = ['3rd']*7 + ['1st']*8 + ['2nd']*8 + ['3rd']27 shifts_dict = dict(zip(hours,shits))2829 conn = connect_db_sql(database="Morganton", user= "postgres", password= "United2018", host="localhost", port="5432")30 df = get_db_sql(conn, query=query)3132 #eliminating duplicates33 df = df[~df.duplicated()]3435 df['date'] = pd.to_datetime(df.date_time.dt.date)36 df['year_month'] = df['date'].apply(lambda date: str(date.year) + '-' + str(date.month))37 df['year_week'] = df['date'].apply(lambda date: str(date.year) + '-' + str(date.week))38 df['week'] = df['date'].dt.week39 df['week'] = df['week'].apply(lambda x: '0' + str(x) if len(str(x))==1 else x).astype('str')40 df['year'] = df['date'].dt.year.astype('str')41 df['year_week'] = df['year'] + '-' + df['week']42 df['year_week_date'] = pd.to_datetime(df.week.astype(str)+ df.year.astype(str).add('-1') ,format='%V%G-%u')43 df['hour'] = df['date_time'].dt.hour44 df['shift'] = df['hour'].map(shifts_dict)45 df = df.rename(columns={'platform':'platform_2', 'platform_consolidated':'platform' })46 df['platform'] = df['platform'].replace('Jeep WK FA ', 'Jeep WK FA')47 df['platform'] = df['platform'].replace('98765432.1', 'Unknown')484950 return df5152@st.cache(allow_output_mutation=True)53def plot_frop_rates(df_dates, freq):54 drop_rate = df_dates.groupby([to_plot_freq[freq],'op090_failed_part'])['platform'].count().reset_index().rename(columns={'platform':'count'})55 drop_rate = pd.pivot_table(drop_rate, values='count', index=to_plot_freq[freq], columns='op090_failed_part')56 drop_rate = drop_rate.fillna(0)57 drop_rate['fail_%'] = drop_rate.iloc[:,1] / (drop_rate.iloc[:,0] + drop_rate.iloc[:,1])*10058 drop_rate['fail_%'] = drop_rate['fail_%'].round(2)59 drop_rate = drop_rate.rename(columns={True: 'OP90 NOK Amount'})60 drop_rate = drop_rate.rename(columns={False: 'OP90 OK Amount'})61 avg_drop_rate = df_dates['op090_failed_part'].mean()*1006263 fig_drop = px.bar(drop_rate, x=drop_rate.index, y='fail_%' , text='fail_%')64 fig_drop.update_traces(marker_color='#798D98', marker_line_color='rgb(8,48,107)', marker_line_width=1.0, opacity=0.6 )65 fig_drop.update_layout(uniformtext_minsize=10, uniformtext_mode='hide')6667 fig_drop.add_hline(y=avg_drop_rate, line_width=1.0, line_dash="solid", line_color="red")68 annotations = [dict(xref='paper', x=1.13, y=avg_drop_rate, xanchor='right', yanchor='middle', text='o.a' + ' {}%'.format(round(avg_drop_rate,2)),69 font=dict(family='Arial',size=13), showarrow=False)]70 fig_drop.update_layout(annotations=annotations)7172 fig_prod = px.bar(drop_rate, x=drop_rate.index, y=['OP90 OK Amount','OP90 NOK Amount'])73 fig_prod.update_traces(marker_line_width=1.0, opacity=0.6)74 fig_prod.update_layout(uniformtext_minsize=10, uniformtext_mode='hide')75 return fig_drop, fig_prod7677@st.cache(allow_output_mutation=True)78def plot_station_distributions_stripplot(df_plat, x, y, font_size, lower_L_show, upper_L_show, line_lower_l, line_upper_l , show_shift, show_limits):79 sns.set_style('darkgrid')80 plt.rcParams.update({'font.size': 6})8182 fig, ax = plt.subplots()83 df_plat = df_plat.sort_values(by='platform', ascending=False)8485 if show_shift== True:86 params = dict(x=x, y=y, data = df_plat, dodge=True, hue='shift')87 else:88 params = dict(x=x, y=y, data = df_plat, dodge=True)8990 sns.stripplot(size=2, **params)91 plt.xlim(lower_L_show,upper_L_show)9293 if show_limits == True:94 plt.axvline(x=line_lower_l, color='red', label='6.8E-05', linestyle='--', linewidth=0.8)95 plt.axvline(x=line_upper_l, color='red', label='6.8E-05', linestyle='--', linewidth=0.8)9697 return fig9899@st.cache(allow_output_mutation=True)100def filter_dates(df, date1, date2):101 df_filtered = df.loc[date1 : date2]102 return df_filtered103104@st.cache(allow_output_mutation=True)105def select_platforms(df, platforms):106 df_dates = df[df['platform'].isin(platforms)]107 return df_dates108109@st.cache(allow_output_mutation=True)110def drop_rates_per_platforms(df_plat):111 df_drop = df_plat.groupby(['platform','op090_failed_part'])['platform_2'].count().reset_index().rename(columns={'platform_2':'count'})112 df_drop = pd.pivot_table(df_drop, values='count', index='platform', columns='op090_failed_part').fillna(0)113 if len(df_drop.columns) < 2:114 df_drop[True]= 0115 df_drop['Fail_%'] = df_drop.iloc[:,1] / (df_drop.iloc[:,1] + df_drop.iloc[:,0])*100116 df_drop['Total'] = df_drop.iloc[:,1] + df_drop.iloc[:,0]117 df_drop = df_drop.sort_values(by='Fail_%')118 df_drop['NOK_%_of_platforms'] = (df_drop[True] / df_drop[True].sum())*100119120 fig_drop_rate = px.bar(df_drop, x="Fail_%", y=df_drop.index, orientation='h', height=300)121 fig_drop_rate.update_traces(marker_color='#308196', marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)122123 fig_oa_drop_percent = px.bar(df_drop, x='NOK_%_of_platforms', y=df_drop.index, orientation='h', height=300)124 fig_oa_drop_percent.update_traces(marker_color='#71978C', marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)125126 return fig_drop_rate, fig_oa_drop_percent127128@st.cache(allow_output_mutation=True)129def nok_cumsum_overtime(df_plat, platforms, line_plot_freq, freq):130 df_nok_total = pd.DataFrame()131 for platform in platforms:132 df_nok = pd.DataFrame()133 df_platform = df_plat[(df_plat['platform'] == platform) & (df_plat['op090_failed_part'] == True) ]134 df_platform['ocurr'] = 1135 df_nok['NOK_cummulative'] = df_platform['ocurr'].resample(line_plot_freq[freq]).sum().cumsum()136 df_nok['platform'] = platform137138 df_nok_total = pd.concat([df_nok_total,df_nok], axis=0)139140 fig = px.line(df_nok_total, x=df_nok_total.index, y="NOK_cummulative", color='platform')141 return fig142143@st.cache(allow_output_mutation=True)144def torque_dist_per_platform(df_plat, single_points ,lower_lim_show, upper_lim_show, lower_l, upper_l, show_shift, show_limits):145 if single_points == True:146 fig= plot_station_distributions_stripplot(df_plat, x='op090 torque [nm]', y='platform', font_size=6, lower_L_show=lower_lim_show,147 upper_L_show=upper_lim_show, line_lower_l=lower_l, line_upper_l=upper_l ,148 show_shift=show_shift, show_limits= show_limits)149 else:150 df_plat_single = df_plat.copy().sort_values(by='platform', ascending=True)151 if show_shift == True:152 fig = px.box(data_frame=df_plat_single, x="op090 torque [nm]", y='platform', range_x=[lower_lim_show,upper_lim_show],153 color="shift", color_discrete_sequence =['#308196','#FFC300 ', '#34BA55'], height=650)154 fig.update_traces(marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)155 else:156 fig = px.box(data_frame=df_plat_single, x="op090 torque [nm]", y='platform', range_x=[lower_lim_show,upper_lim_show], height=650)157 fig.update_traces(marker_color='#308196', marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)158159 # Lines ----------160 if show_limits == True:161 fig.add_vline(x=lower_l, line_width=1.0, line_dash="dash", line_color="red")162 fig.add_vline(x=upper_l, line_width=1.0, line_dash="dash", line_color="red")163 return fig164165@st.cache(allow_output_mutation=True)166def angle_dist_per_platform(df_plat, single_points ,angle_lower_lim_show, angle_upper_lim_show, angle_lower_l, angle_upper_l, show_shift, show_angle_limits):167 if single_points:168 fig= plot_station_distributions_stripplot(df_plat, x='op090 angle [°]', y='platform', font_size=6, lower_L_show=angle_lower_lim_show,169 upper_L_show=angle_upper_lim_show, line_lower_l=angle_lower_l, line_upper_l=angle_upper_l ,170 show_shift=show_shift, show_limits= show_angle_limits)171 else:172 df_plat_single = df_plat.copy().sort_values(by='platform', ascending=True)173 if show_shift == True:174 fig = px.box(data_frame=df_plat_single, x="op090 angle [°]", y='platform', range_x=[angle_lower_lim_show,angle_upper_lim_show],175 color="shift", color_discrete_sequence =['#308196','#FFC300 ', '#34BA55'], height=650)176 fig.update_traces(marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)177 else:178 fig = px.box(data_frame=df_plat_single, x="op090 angle [°]", y='platform', range_x=[angle_lower_lim_show,angle_upper_lim_show], height=650)179 fig.update_traces(marker_color='#308196', marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)180181 # Lines ----------182 if show_angle_limits == True:183 fig.add_vline(x=angle_lower_l, line_width=1.0, line_dash="dash", line_color="red")184 fig.add_vline(x=angle_upper_l, line_width=1.0, line_dash="dash", line_color="red")185 return fig186187188@st.cache(allow_output_mutation=True)189def plot_torque_vs_angle(df_plat, show_limits ,lower_l, upper_l, angle_lower_lim_show,angle_upper_lim_show, lower_lim_show,upper_lim_show):190 fig = px.scatter(df_plat, x='op090 angle [°]', y="op090 torque [nm]", color="platform", range_x=[angle_lower_lim_show,angle_upper_lim_show], range_y=[lower_lim_show,upper_lim_show],191 opacity=0.5, title='Torque vs Angle')192 if show_limits == True:193 fig.add_hline(y=lower_l, line_width=1.0, line_dash="dash", line_color="red")194 fig.add_hline(y=upper_l, line_width=1.0, line_dash="dash", line_color="red")195 return fig196197@st.cache(allow_output_mutation=True)198def plot_torque_vs_angle_singleplat(df_plat, show_limits ,lower_l, upper_l, angle_lower_lim_show,angle_upper_lim_show, lower_lim_show,upper_lim_show):199 fig = px.scatter(df_plat, x='op090 angle [°]', y="op090 torque [nm]", color="op090_failed_part", range_x=[angle_lower_lim_show,angle_upper_lim_show], range_y=[lower_lim_show,upper_lim_show],200 opacity=0.5)201 if show_limits == True:202 fig.add_hline(y=lower_l, line_width=1.0, line_dash="dash", line_color="red")203 fig.add_hline(y=upper_l, line_width=1.0, line_dash="dash", line_color="red")204 return fig205206@st.cache(allow_output_mutation=True)207def plot_torque_angle_overtime(df_platform,platform_to_show, to_plot_freq ,freq, lower_lim_show,upper_lim_show,show_limits, lower_l, upper_l, angle_lower_lim_show,angle_upper_lim_show,show_angle_limits ,angle_lower_l, angle_upper_l):208 fig_torque = px.scatter(df_platform, y='op090 torque [nm]', x=to_plot_freq[freq], color="op090_failed_part", range_y=[lower_lim_show,upper_lim_show],209 opacity=0.5, title=platform_to_show + ' Torque over time', height=400)210 if show_limits == True:211 fig_torque.add_hline(y=lower_l, line_width=1.0, line_dash="dash", line_color="red")212 fig_torque.add_hline(y=upper_l, line_width=1.0, line_dash="dash", line_color="red")213214 #-----------------------------------------------------------------------215216 fig_angle = px.scatter(df_platform, y='op090 angle [°]', x=to_plot_freq[freq], color="op090_failed_part", range_y=[angle_lower_lim_show,angle_upper_lim_show],217 opacity=0.5, title=platform_to_show + ' Angle over time')218 if show_angle_limits == True:219 fig_angle.add_hline(y=angle_lower_l, line_width=1.0, line_dash="dash", line_color="red")220 fig_angle.add_hline(y=angle_upper_l, line_width=1.0, line_dash="dash", line_color="red")221222 return fig_torque, fig_angle223224@st.cache(allow_output_mutation=True)225def drop_rate_per_angle_bins(df_platform):226 df_platform['angle bins'] = pd.cut( df_platform["op090 angle [°]"], bins= list(np.arange(1.0,180.0,5.0))).astype('str')227 drop_rate = df_platform.groupby(['angle bins','op090_failed_part'])['platform'].count().reset_index().rename(columns={'platform':'count'})228 drop_rate = pd.pivot_table(drop_rate, values='count', index='angle bins', columns='op090_failed_part')229 drop_rate = drop_rate.fillna(0)230 if len(drop_rate.columns) < 2:231 drop_rate[True]= 0232 drop_rate['fail_%'] = drop_rate.iloc[:,1] / (drop_rate.iloc[:,0] + drop_rate.iloc[:,1])*100233 drop_rate = drop_rate.rename(columns={True: 'OP90 NOK Amount'})234 drop_rate =drop_rate.round(2)235 fig = px.bar(drop_rate, x=drop_rate.index, y='fail_%' , text='fail_%', title='OP90 Drop rate % vs angle bins')236 fig.update_traces(marker_color='#308196', marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)237238 return fig239240@st.cache(allow_output_mutation=True)241def plot_single_day_torque(day, df_plat,show_shift ,lower_lim_show , show_limits, upper_lim_show, lower_l, upper_l):242 df_day_plot = df_plat.loc[str(day)]243 if show_shift == True:244 fig = px.scatter(df_day_plot, x = 'hour', y = 'op090 torque [nm]', range_y=[lower_lim_show, upper_lim_show],245 color='shift', color_discrete_sequence =['#308196','#FFC300 ', '#34BA55'])246 fig.update_traces(marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)247 else:248 fig = px.scatter(df_day_plot, x = 'hour', y = 'op090 torque [nm]', range_y=[lower_lim_show, upper_lim_show])249 fig.update_traces(marker_color='#308196', marker_line_color='rgb(8,48,107)', marker_line_width=0.5, opacity=0.6)250 # Lines ----------251 if show_limits == True:252 fig.add_hline(y=lower_l, line_width=1.0, line_dash="dash", line_color="red")253 fig.add_hline(y=upper_l, line_width=1.0, line_dash="dash", line_color="red")254255 return fig256257to_plot_freq = {'day' : 'date', 'week': 'year_week_date', 'month': 'year_month' }258line_plot_freq = {'day' : 'D', 'week': 'W', 'month': 'M' }259torque_limits = {'WL FA': [52.0,56.0], 'Ram DT FA': [52.0, 56.0], 'Ford FA': [46.7, 63.3], 'Jeep WK FA': [48.0, 52.0], 'HONDA FA': [55,60]}260angle_limits = {'WL FA': [1.0,90.0], 'Ram DT FA': [1.0, 90.0], 'Jeep WK FA': [1.0, 90.0], 'HONDA FA': [0,6000]}261262def app():263 #Platform Selection side bar and others ------------------------------------264 with st.sidebar:265 from_date = (datetime.date.today() - DateOffset(months=2)).date()266 st.subheader('From what date to load sql data?')267 d1 = st.date_input("", from_date)268269 #date range270 st.write("### Date range to analyze")271 col1, col2 = st.beta_columns(2)272 day_from= col1.date_input("From date", from_date, min_value=d1)273 day_up_to= col2.date_input("Up to date", datetime.date.today(), min_value=day_from + DateOffset(days=2))274275 # query to get data -------------------276 query = "select * from hlt_op090_from_200_210 where date_time > '%s'" %(str(d1))277 df= long_running_function_to_load_data(query = query)278 #Date range Leak Distribution Plot and Srop rate plot--------------279 df_dates = filter_dates(df, str(day_from), str(day_up_to))280 #Checking wha tplatform are present in date range281 platforms = list(df_dates['platform'].unique())282283 with st.sidebar:284 #Selecting platforms285 st.subheader('Platforms to compare:')286 platforms = st.multiselect('',platforms, platforms[:5], key='platform_select')287 #freq288 freq = st.selectbox('Select frequency to analyze:', ('day','week','month'))289 show_shift = st.checkbox('Show Shift Comparison?')290291 st.markdown("""---""")292 st.subheader('Torque Limits')293 #Limits to show294 lower_lim_show, upper_lim_show = st.slider('Select torque range to plot:', 0.0, 80.0, (46.0,61.0) ,1.0)295296 #limit lines to show297 show_limits = st.checkbox('Show torque limits?')298 lower_l = 52.0299 upper_l = 56.0300 if show_limits == True:301 limit_to_show = st.selectbox('Select limits to plot:', ('Manually','WL FA','Jeep WK FA','Ram DT FA','Ford FA','HONDA FA'))302 if limit_to_show == 'Manually':303 col1, col2 = st.beta_columns(2)304 lower_l = col1.slider("Lower limit:", 0.0, 80.0, 52.0, 0.5, key='lower_limit_0')305 upper_l = col2.slider("Upper limit:", 0.0, 80.0, 56.0, 0.5, key='upper_limit_0')306 else:307 lower_l = torque_limits[limit_to_show][0]308 upper_l = torque_limits[limit_to_show][1]309 st.markdown("""---""")310311 #limit lines to show312 st.subheader('Angle Limits')313 angle_lower_lim_show, angle_upper_lim_show = st.slider('Select angle range to plot:', 0.0, 360.0, (5.0,180.0) ,5.0)314 show_angle_limits = st.checkbox('Show angle limits?')315 angle_lower_l = 0316 angle_upper_l = 90317 if show_angle_limits == True:318 angle_limit_to_show = st.selectbox('Select angle limits to plot:', ('Manually','WL FA','Jeep WK FA','Ram DT FA'))319 if angle_limit_to_show == 'Manually':320 col1, col2 = st.beta_columns(2)321 angle_lower_l = col1.slider("Lower limit:", 0.0, 360.0, 1.0, 0.5, key='lower_limit_1')322 angle_upper_l = col2.slider("Upper limit:", 0.0, 360.0, 90.0, 0.5, key='upper_limit_1')323 else:324 angle_lower_l = angle_limits[angle_limit_to_show][0]325 angle_upper_l = angle_limits[angle_limit_to_show][1]326 st.markdown("""---""")327328329 #Filtering Platforms ////////////////////////////////////////////////////330 df_plat = select_platforms(df_dates, platforms)331332 st.title("OP090 Test 3 Station ")333 st.write('# Platform Comparison')334335336 st.write("## Select Analysis")337 analysis = st.selectbox('', ("ALL Platforms",'Single Platform',"Single Day Analysis"))338 st.markdown("""---""")339340 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////341 # /342 # PLATFORMS /343 # /344 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////345346 if analysis == "ALL Platforms":347348 #1st and 2nd PLOT349 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////350 st.subheader('Drop Rate % on OP90 per platform')351 fig_drop_rate, fig_oa_drop_percent = drop_rates_per_platforms(df_plat)352 st.write(fig_drop_rate)353 st.subheader('% of NOK with respect to all NOK of current platforms selected')354 st.write(fig_oa_drop_percent)355356357 #3rd PLOT358 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////359 #NOK cummulatives over time360 st.subheader('Platforms NOK cummulative over time per ' + freq)361 fig = nok_cumsum_overtime(df_plat, platforms, line_plot_freq, freq)362 st.write(fig)363364365 #4th PLOT366 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////367 # torque Distribution per platform -----------------------------------------------------------------368 st.subheader('Torque per platform')369 single_points = st.checkbox("Show single points (slower)", False)370 fig = torque_dist_per_platform(df_plat, single_points ,lower_lim_show, upper_lim_show, lower_l, upper_l, show_shift, show_limits)371 if single_points == True:372 st.pyplot(fig)373 else:374 st.plotly_chart(fig)375376377 #5th PLOT378 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////379 st.subheader('Angle per platform')380 single_points = st.checkbox("Show single points (slower)", False, key='angle_single_points')381 fig = angle_dist_per_platform(df_plat, single_points ,angle_lower_lim_show, angle_upper_lim_show, angle_lower_l, angle_upper_l, show_shift, show_angle_limits)382 if single_points == True:383 st.pyplot(fig)384 else:385 st.plotly_chart(fig)386387388 #6th PLOT389 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////390 #Torque vs angle391 fig = plot_torque_vs_angle(df_plat, show_limits ,lower_l, upper_l, angle_lower_lim_show,angle_upper_lim_show, lower_lim_show,upper_lim_show)392 st.write(fig)393394 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////395 # /396 # SINGLE PLATFORM /397 # /398 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////399400 elif analysis == 'Single Platform':401402 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////403 st.subheader('Single PLatform Analysis')404 platform_to_show = st.selectbox('Platform to show:', platforms)405 df_platform = df_plat[df_plat['platform']== platform_to_show]406407 #7th and 8th PLOT408 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////409 fig_torque,fig_angle = plot_torque_angle_overtime(df_platform,platform_to_show, to_plot_freq ,freq, lower_lim_show,upper_lim_show,show_limits, lower_l, upper_l, angle_lower_lim_show,angle_upper_lim_show,show_angle_limits ,angle_lower_l, angle_upper_l)410 st.write(fig_torque)411 st.write(fig_angle)412413414 #9th and 10th PLOT415 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////416 st.write(platform_to_show+ ' - OP90 Drop Rate')417418 c1,c2,c3 = st.beta_columns(3)419 c1.markdown('1st Shift: ' + str(round(df_platform[df_platform['shift'] == '1st']['op090_failed_part'].mean()*100,2) ) + '% Fail')420 c2.markdown('2nd Shift: ' + str(round(df_platform[df_platform['shift'] == '2nd']['op090_failed_part'].mean()*100,2) ) + '% Fail')421 c3.markdown('3rd Shift: ' + str(round(df_platform[df_platform['shift'] == '3rd']['op090_failed_part'].mean()*100,2) ) + '% Fail')422423 fig_prod, fig_drop = plot_frop_rates(df_platform, freq)424425 st.write(fig_prod)426 st.write(fig_drop)427428429 #11th PLOT430 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////431 st.write(platform_to_show + ' - Torque vs Angle')432 fig = plot_torque_vs_angle_singleplat(df_platform, show_limits ,lower_l, upper_l, angle_lower_lim_show,angle_upper_lim_show, lower_lim_show,upper_lim_show)433 st.write(fig)434435436 #12th PLOT437 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////438 fig = drop_rate_per_angle_bins(df_platform)439 st.write(fig)440441 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////442 # /443 # SINGLE DAY /444 # /445 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////446447 elif analysis == "Single Day Analysis":448 #13th PLOT449 #////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////450 platform_to_show = st.selectbox('Platform to show:', platforms)451 df_platform = df_plat[df_plat['platform']== platform_to_show]452 st.subheader(platform_to_show+ ' - Single day torque rates')453 col1, _ , _, _= st.beta_columns(4)454 day = col1.date_input("Select day to plot", datetime.date.today())455456 if str(day) in df_plat.index:457 fig = plot_single_day_torque(day,df_platform,show_shift, lower_lim_show , show_limits, upper_lim_show, lower_l, upper_l)458 st.write(fig)459460 else: ...

Full Screen

Full Screen

function.py

Source:function.py Github

copy

Full Screen

1import core2from javax.swing import *3from javax.swing.event import *4from java.awt import *5from java.awt.event import *6from java.util import Hashtable7import random8from math import floor9from math import ceil10import java11class FunctionControl(core.DataViewComponent, ComponentListener):12 def __init__(self, view, name, func, label=None):13 core.DataViewComponent.__init__(self, label)14 self.view = view15 self.name = name16 self.func = func17 self.label_height = 1818 self.resize_border = 219 self.popup_hide_limit = JCheckBoxMenuItem('auto-hide limits', True, actionPerformed=self.toggle_autohide)20 self.popup.add(self.popup_hide_limit)21 self.show_limits = False22 self.auto_hide_limits = True23 self.limits_font = Font("Dialog", Font.PLAIN, 10)24 self.limit_width = 025 self.limit_hide_delay = 100026 self.limit_color_def = 0.327 self.limit_color_val = self.limit_color_def28 self.limit_color_step = (1 - self.limit_color_def) / 1029 self.limit_hide_timer = Timer(self.limit_hide_delay / 10, None, actionPerformed=self.hide_limits)30 self.limit_hide_timer.setRepeats(False)31 self.popup.add(JPopupMenu.Separator())32 self.popup.add(JMenuItem('zero', actionPerformed=self.zero))33 self.popup.add(JMenuItem('set value', actionPerformed=self.set_value))34 self.filename = None35 self.popup.add(JMenuItem('set from file...', actionPerformed=self.set_from_file))36 self.popup.add(JPopupMenu.Separator())37 self.popup.add(JMenuItem('increase range', actionPerformed=self.increase_range))38 self.popup.add(JMenuItem('decrease range', actionPerformed=self.decrease_range))39 self.scale_factor = 0.0140 self.range = 1.041 self.data = self.view.watcher.watch(name, func)42 values = self.data.get_first()43 self.sliders = []44 self.labels = []45 for i, v in enumerate(values):46 vv = int(v * 100 / self.range)47 if vv > 100:48 vv = 10049 if vv < -100:50 vv = -10051 slider = JSlider(JSlider.VERTICAL, -100, 100, vv, stateChanged=lambda event, index=i: self.slider_moved(index))52 slider.background = Color.white53 self.add(slider)54 self.sliders.append(slider)55 label = JLabel('0.00')56 self.add(label)57 self.labels.append(label)58 slider.addMouseListener(self)59 self.setSize(len(values) * 40 + 40, 200)60 self.addComponentListener(self)61 self.componentResized(None)62 def increase_range(self, event):63 self.range *= 2.064 self.check_label_size()65 self.repaint()66 def decrease_range(self, event):67 self.range *= 0.568 self.check_label_size()69 self.repaint()70 def check_label_size(self):71 if(self.show_limits):72 limit_label = JLabel(("-%1.2f" % (self.range)))73 limit_width = limit_label.getPreferredSize().width - self.sliders[0].width / 274 if(limit_width != self.limit_width):75 self.setSize(self.size.width + limit_width - self.limit_width, self.size.height)76 self.setLocation(self.x - limit_width + self.limit_width, self.y)77 self.limit_width = limit_width78 def zero(self, event):79 for i in range(len(self.sliders)):80 self.set_slider_value(i, 0)81 def set_value(self, event):82 try:83 example = ','.join(['%1.1f' % random.uniform(-5, 5) for i in range(len(self.sliders))])84 text = JOptionPane.showInputDialog(self.view.frame, 'Enter input value. \nExample: %s' % example, "Set value", JOptionPane.PLAIN_MESSAGE, None, None, None)85 v = eval(text)86 if isinstance(v, (int, float)):87 v = [v]88 if len(v) > len(self.sliders):89 v = v[:len(self.sliders)]90 for i, vv in enumerate(v):91 self.set_slider_value(i, vv)92 except:93 self.release_value(event)94 def set_from_file(self, event):95 fileChooser = JFileChooser()96 if self.filename is not None:97 fileChooser.setSelectedFile(java.io.File(self.filename))98 if fileChooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION:99 self.filename = fileChooser.selectedFile.absolutePath100 #TODO: this doesn't for for nested FunctionInputs101 input = self.view.network.getNode(self.name)102 from nef.functions import Interpolator103 interp = Interpolator(self.filename)104 interp.load_into_function(input)105 def set_slider_value(self, index, value):106 sv = value / (self.scale_factor * self.range)107 self.sliders[index].value = int(sv)108 self.labels[index].text = '%1.2f' % value109 self.check_label_size()110 self.repaint()111 if self.view.paused: # change immediately, bypassing filter112 self.data.data[-1][index] = value113 self.view.forced_origins_prev[(self.name, 'origin', index)] = value114 self.view.forced_origins[(self.name, 'origin', index)] = value115 def slider_moved(self, index):116 if self.sliders[index].valueIsAdjusting: # if I moved it117 v = self.sliders[index].value * self.scale_factor * self.range118 self.labels[index].text = '%1.2f' % v119 if self.view.paused: # change immediately, bypassing filter120 self.data.data[-1][index] = v121 self.view.forced_origins_prev[(self.name, 'origin', index)] = v122 self.view.forced_origins[(self.name, 'origin', index)] = v123 def paintComponent(self, g):124 temp = self.show_label125 self.show_label = False126 core.DataViewComponent.paintComponent(self, g)127 self.show_label = temp128 if self.show_label:129 g.color = Color(0.3, 0.3, 0.3)130 bounds = g.font.getStringBounds(self.label, g.fontRenderContext)131 g.drawString(self.label, (self.size.width - self.limit_width) / 2 - bounds.width / 2 + self.limit_width, bounds.height)132 self.active = self.view.current_tick >= self.view.timelog.tick_count - 1133 data = self.data.get(start=self.view.current_tick, count=1)[0]134 if data is None:135 data = self.data.get_first()136 if(self.show_limits):137 g.color = Color(self.limit_color_val, self.limit_color_val, self.limit_color_val)138 txt_min = "%1.2f" % (-self.range)139 txt_max = "%1.2f" % (self.range)140 temp_font = g.font141 g.font = self.limits_font142 bounds_min = g.font.getStringBounds(txt_min, g.fontRenderContext)143 bounds_max = g.font.getStringBounds(txt_max, g.fontRenderContext)144 g.drawString(txt_max, 10 + bounds_min.width - bounds_max.width, self.resize_border + self.label_offset + bounds_max.height)145 g.drawString(txt_min, 10, self.height - self.resize_border - self.labels[0].getPreferredSize().height - bounds_min.height)146 g.font = temp_font147 for i, v in enumerate(data):148 while v > self.range * 1.1:149 self.range *= 2150 while v < -self.range * 1.1:151 self.range *= 2152 for i, v in enumerate(data):153 sv = int(v * 100.0 / self.range)154 if sv > 100:155 sv = 100156 if sv < -100:157 sv = -100158 if not self.sliders[i].valueIsAdjusting:159 self.sliders[i].value = sv160 self.labels[i].text = '%1.2f' % v161 self.sliders[i].enabled = self.active162 self.componentResized(None)163 def componentResized(self, e):164 w = self.width - self.resize_border * 2 - self.limit_width165 dw = w / len(self.sliders)166 x = (dw - self.sliders[0].minimumSize.width) / 2167 for i, slider in enumerate(self.sliders):168 slider.setLocation(self.limit_width + self.resize_border + x + i * dw, self.resize_border + self.label_offset)169 slider.setSize(slider.minimumSize.width, self.height - self.resize_border * 2 - 20 - self.label_offset)170 self.labels[i].setLocation(slider.x + slider.width / 2 - self.labels[i].width / 2, slider.y + slider.height)171 def componentHidden(self, e):172 pass173 def componentMoved(self, e):174 pass175 def componentShown(self, e):176 pass177 def save(self):178 info = core.DataViewComponent.save(self)179 if(self.auto_hide_limits):180 self.hide_limits(None)181 info['x'] = self.x # Overwrite x and width to account for removed limits182 info['width'] = self.width183 info['range'] = self.range184 info['limits'] = self.auto_hide_limits185 info['limits_w'] = self.limit_width186 return info187 def restore(self, d):188 core.DataViewComponent.restore(self, d)189 self.range = d.get('range', 1.0)190 self.auto_hide_limits = d.get('limits', True)191 self.limit_width = d.get('limits_w', 0)192 self.popup_hide_limit.state = self.auto_hide_limits193 self.show_limits = not self.auto_hide_limits194 def mouseEntered(self, event):195 if(self.auto_hide_limits):196 self.disp_limits()197 core.DataViewComponent.mouseEntered(self, event)198 def mouseExited(self, event):199 if(self.auto_hide_limits):200 self.limit_hide_timer.start()201 core.DataViewComponent.mouseExited(self, event)202 def toggle_autohide(self, event):203 self.auto_hide_limits = event.source.state204 if(self.auto_hide_limits):205 self.limit_hide_timer.start()206 else:207 self.disp_limits()208 def disp_limits(self):209 if(not self.show_limits):210 limit_label = JLabel(("-%1.2f" % (self.range)))211 self.limit_width = limit_label.getPreferredSize().width - self.sliders[0].width / 2212 self.setSize(self.size.width + self.limit_width, self.size.height)213 self.setLocation(self.x - self.limit_width, self.y)214 self.limit_hide_timer.stop()215 self.limit_color_val = self.limit_color_def216 self.show_limits = True217 self.repaint()218 def hide_limits(self, event):219 if(self.show_limits):220 if(self.limit_color_val >= 1 - self.limit_color_step):221 self.limit_hide_timer.stop()222 self.setSize(self.size.width - self.limit_width, self.size.height)223 self.setLocation(self.x + self.limit_width, self.y)224 self.limit_width = 0225 self.show_limits = False226 else:227 self.limit_color_val += self.limit_color_step228 self.limit_color_val = min(self.limit_color_val, 1.0)229 self.limit_hide_timer.start()...

Full Screen

Full Screen

render.py

Source:render.py Github

copy

Full Screen

1# This file is part of Nuntiare project.2# The COPYRIGHT file at the top level of this repository3# contains the full copyright notices and license terms.4import cairo5from . pages import Pages6from . cairo_item import CairoItem7from .. render import Render8class CairoRender(Render):9 def __init__(self, extension):10 super(CairoRender, self).__init__(extension=extension)11 self.surface = None12 self.pages = None # public for test purposes13 def render(self, report, overwrite):14 super(CairoRender, self).render(report, overwrite)15 result = report.result16 # TODO. For test purposes.17 # It should be an option for18 # comand line utility19 show_limits = False20 self.pages = Pages(report)21 if self.extension == 'pdf':22 self.surface = cairo.PDFSurface(23 self.result_file, result.width, result.height)24 elif self.extension == 'svg':25 self.surface = cairo.SVGSurface(26 self.result_file, result.width, result.height)27 ctx = cairo.Context(self.surface)28 page_top = result.margin_top29 footer_top = result.margin_top + result.body.available_height30 if result.header:31 page_top += result.header.height32 footer_top += result.header.height33 for page in self.pages.pages:34 # Print body style35 CairoItem._draw_rectangle(36 ctx, result.body.style,37 page_top, result.margin_left,38 result.body.available_height,39 result.available_width)40 CairoItem.start_clip_area(41 ctx, page_top, result.margin_left,42 result.available_width,43 result.body.available_height,44 result.body.style)45 for f in page.frames:46 frame_left = f.left + result.margin_left47 ctx.set_line_width(0.5)48 if show_limits:49 ctx.set_source_rgb(0, 0, 0)50 ctx.rectangle(51 frame_left,52 page_top,53 f.drawable_width,54 f.height)55 ctx.stroke()56 CairoItem.start_clip_area(57 ctx, page_top, frame_left,58 f.drawable_width, f.height,59 None)60 self._print_items(61 ctx, f.cairo_items,62 page_top, frame_left)63 CairoItem.finish_clip_area(ctx)64 CairoItem.finish_clip_area(ctx)65 if result.header:66 self._print_header_footer(67 ctx, page.header, show_limits,68 result.margin_left,69 result.margin_top,70 result.available_width)71 if result.footer:72 self._print_header_footer(73 ctx, page.footer, show_limits,74 result.margin_left,75 footer_top,76 result.available_width)77 self.surface.show_page()78 self.surface.finish()79 def _print_header_footer(80 self, ctx, header_footer, show_limits,81 left, top, width):82 if not header_footer:83 return84 if show_limits:85 ctx.set_line_width(0.5)86 ctx.set_source_rgb(0, 0, 0)87 ctx.rectangle(88 left, top, width,89 header_footer.height)90 ctx.stroke()91 # Print style92 CairoItem._draw_rectangle(93 ctx, header_footer.definition.style,94 top, left,95 header_footer.definition.available_height,96 width)97 CairoItem.start_clip_area(98 ctx, top, left,99 width, header_footer.height,100 header_footer.definition.style)101 self._print_items(102 ctx, header_footer.cairo_items, top, left)103 CairoItem.finish_clip_area(ctx)104 def _print_items(self, ctx, items, top, left):105 for it in items:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tempest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful