def _draw_aggrid_df(self, expander, df): with expander: if df.empty: st.info('No matching result found') elif 'error' in df: st.error(df['error'][0]) else: gb = GridOptionsBuilder.from_dataframe(df) gb.configure_pagination(paginationPageSize=25) gb.configure_default_column(floatingFilter=True, editable=False, selectable=False) gb.configure_grid_options(domLayout='normal', preventDefaultOnContextMenu=True) gridOptions = gb.build() if df.shape[0] == 1: height = 150 elif df.shape[0] < 4: height = 200 else: height = 400 _ = AgGrid(df, height=height, gridOptions=gridOptions, allow_unsafe_jscode=True, update_mode=GridUpdateMode.NO_UPDATE, theme='streamlit', key=str(randint(1, 10000000)))
def _draw_aggrid_df(self, df): gb = GridOptionsBuilder.from_dataframe(df) gb.configure_pagination(paginationPageSize=25) gb.configure_default_column(floatingFilter=True) if 'error' in df.columns: jscode = self._aggrid_style() gb.configure_column("error", floatingFilter=True, cellStyle=jscode, editable=False) gb.configure_grid_options(domLayout='normal', preventDefaultOnContextMenu=True) gridOptions = gb.build() gridOptions['getRowStyle'] = self._aggrid_style_rows(df) _ = AgGrid( df, gridOptions=gridOptions, allow_unsafe_jscode=True, update_mode=GridUpdateMode.NO_UPDATE, theme='streamlit', )
def _draw_aggrid_df(self, df) -> AgGrid: gb = GridOptionsBuilder.from_dataframe(df) gb.configure_pagination(paginationPageSize=25) gb.configure_default_column(floatingFilter=True, selectable=False) gb.configure_grid_options(domLayout='normal') gridOptions = gb.build() gridOptions['rowStyle'] = {'background': 'white'} jscode = self._aggrid_style_rows() gridOptions['getRowStyle'] = jscode if self._state.experimental_ok: retmode = 'FILTERED' upd8_mode = GridUpdateMode.FILTERING_CHANGED else: retmode = 'AS_INPUT' upd8_mode = GridUpdateMode.VALUE_CHANGED grid_response = AgGrid( df, gridOptions=gridOptions, allow_unsafe_jscode=True, data_return_mode=retmode, update_mode=upd8_mode, theme='streamlit', key='xplore_show_tbl', ) return grid_response
def configure_grid_stat(df): gb = GridOptionsBuilder.from_dataframe(df) gb.configure_default_column(editable=False) # gb.configure_side_bar() gb.configure_selection("multiple", use_checkbox=False,rowMultiSelectWithClick=True, suppressRowDeselection=False) # gb.configure_grid_options(domLayout='autoHeight') gb.configure_grid_options(domLayout='normal') gridOptions = gb.build() return gridOptions
def configure_grid_detail(df): gb = GridOptionsBuilder.from_dataframe(df) # gb.configure_default_column(groupable=False, value=True, enableRowGroup=False, editable=False) # gb.configure_side_bar() gb.configure_default_column(editable=False) gb.configure_column("sentence",initialPinned="left") # gb.configure_column("client_id",hide=True) gb.configure_selection("single", use_checkbox=False) gb.configure_pagination(paginationAutoPageSize=True) gb.configure_grid_options(domLayout='normal') gridOptions = gb.build() return gridOptions
def files_select_ag_grid(add_current=False, mode="single"): file_list = [ x.replace(".pickle", "") for x in list_dir("saved_sessions") if ".pickle" in x ] file_times = [ # datetime.datetime.fromtimestamp( get_m_time(os.path.join("saved_sessions", f"{x}.pickle")) # ) for x in file_list ] files_desc = [] for f_name in file_list: desc_f_name = os.path.join("saved_sessions", f"{f_name}.txt") if file_exists(desc_f_name): files_desc.append(open_file(desc_f_name).read()) else: files_desc.append("") if add_current: file_list = ["Análise Atual"] + file_list file_times = [""] + file_times files_desc = [""] + files_desc input_df = pd.DataFrame( list(zip(file_list, file_times, files_desc)), columns=["Nome", "Ùltima Modificação", "Descrição"], ) gb = GridOptionsBuilder.from_dataframe(input_df) gb.configure_selection(mode, use_checkbox=True) gridOptions = gb.build() update_mode_value = GridUpdateMode.__members__["MODEL_CHANGED"] return AgGrid( input_df, gridOptions=gridOptions, update_mode=update_mode_value, height=200, )
def aggriddf(df): gb = GridOptionsBuilder.from_dataframe(df) gb.configure_default_column(groupable=True, value=True, enableRowGroup=True, aggFunc='sum', editable=False) gb.configure_grid_options(domLayout='normal') #gb.configure_side_bar() gridOptions = gb.build() grid_response = AgGrid( df, gridOptions=gridOptions, height=330, width='100%', #data_return_mode=return_mode_value, #update_mode=update_mode_value, allow_unsafe_jscode= True, #Set it to True to allow jsfunction to be injected enable_enterprise_modules=False, ) return grid_response
reputación que es compartida entre todos los comerciantes participantes. Incluso los comerciantes recién iniciados en el mundo de las ventas pueden beneficiarse de espacios privilegiados, campañas y otras facilidades que sólo un servicio como el de olist puede ofrecer. ''') if session_state.Session is True: if LogOut.button('LogOut'): session_state.Session = False st.experimental_rerun() st.header('Tu historial de reviews') Summary_Rev, Product_Detail = st.beta_columns(2) with Summary_Rev: user_Rev = mt.get_UserRev(userName) gb = GridOptionsBuilder.from_dataframe(user_Rev) cellsytle_jscode = JsCode(""" function(params) { if (params.value == 'A') { return { 'color': 'white', 'backgroundColor': 'darkred' } } else { return { 'color': 'black', 'backgroundColor': 'white' } } }; """)
import streamlit as st import pandas as pd import numpy as np from st_aggrid import AgGrid, GridOptionsBuilder df = pd.DataFrame( np.random.randint(0, 100, 50).reshape(-1, 5), index=range(10), columns=list("abcde"), ) available_themes = ["streamlit", "light", "dark", "blue", "fresh", "material"] selected_theme = st.selectbox("Theme", available_themes) gb = GridOptionsBuilder.from_dataframe(df) if st.checkbox('Pre-select rows 4 and 6 when loading.'): gb.configure_selection('multiple', pre_selected_rows=[3, 5]) response = AgGrid(df, editable=True, gridOptions=gb.build(), data_return_mode="filtered_and_sorted", update_mode="no_update", fit_columns_on_grid_load=True, theme=selected_theme)
metric_selections, default="accuracy") add_btn = trainer_container.button("Add Trainer") if add_btn: sessions.trainer_dict["dataloader"].append(data_selectBox) sessions.trainer_dict["model"].append(model_selectBox) sessions.trainer_dict["loss"].append(loss_selectBox) sessions.trainer_dict["optimizer"].append(optimizer_selectBox) sessions.trainer_dict["scheduler"].append(scheduler_selectBox) sessions.trainer_dict["metrics"].append(metric_selects) sessions.trainer_dict["id"].append(sessions.id) sessions.id = sessions.id + 1 trainer_dataFrame = pd.DataFrame(sessions.trainer_dict) gb = GridOptionsBuilder.from_dataframe(trainer_dataFrame) gb.configure_selection('multiple', use_checkbox=False, rowMultiSelectWithClick=False, suppressRowDeselection=True) gridOptions = gb.build() grid_response = AgGrid(trainer_dataFrame, gridOptions=gridOptions, height=180, width='100%', data_return_mode=DataReturnMode.FILTERED, update_mode=GridUpdateMode.MODEL_CHANGED, fit_columns_on_grid_load=True, allow_unsafe_jscode=True, enable_enterprise_modules=True) trainer_res = grid_response['selected_rows']
def verifier_page(): st.set_page_config(page_title="SPOC Verifier", layout="wide") main_col, geo_col, action_col = st.beta_columns([2, 1, 0.5]) species = pd.read_json("data/species-records.json") grid_options = GridOptionsBuilder.from_dataframe(species) # Grid options grid_options.configure_selection("single", use_checkbox=True) grid_options.configure_pagination(paginationAutoPageSize=True) with main_col: """ # SPOC Verifier """ records_grid = AgGrid( species, gridOptions=grid_options.build(), data_return_mode=DataReturnMode.FILTERED, update_mode=GridUpdateMode.MODEL_CHANGED, ) selected = records_grid["selected_rows"] with geo_col: if len(selected) > 0: f""" ## {selected[0]['Species']} """ url_params = url_parse.urlencode({ "div_num": selected[0]["div_enum"], "paper_id": selected[0]["Paper ID"], "species_id": selected[0]["Instance ID"], }) div_url = f"{settings.api_url}/api/div/?{url_params}" result = requests.get(div_url) entities_html = entities_template.render( content=result.json().get("html")) components.html(entities_html, height=500, scrolling=True) with action_col: action_html = action_template.render(status="select") components.html(action_html, height=75, width=65) if len(selected) > 0: """ ## Places """ geo_request = requests.get( f"{settings.api_url}/api/coordinates/?places={selected[0]['Place']}" ) geo_result = geo_request.json() if len(geo_result) < 1: st.text("No places found") else: m = folium.Map( location=[geo_result["lat_mean"], geo_result["long_mean"]], zoom_start=7) for place in geo_result["markers"]: folium.Marker( [place["latitude"], place["longitude"]], popup=place["label"], tooltip=place["label"], ).add_to(m) folium_static(m)
by=['points_next_event'], ascending=False) grouped_golfers_last_8 = grouped_golfers_last_8.reset_index().drop('index', axis=1) cols_to_move = [ 'Name', 'number_events', 'Week', 'last_8_rank', 'median_rank', 'total_med_rank', 'pos_next_event', 'total_rank', 'points_next_event', 'cum_median_rank', 'cum_8_rank', 'cum_8_median_rank', 'cum_8_exp4_rank' ] cols = cols_to_move + [ col for col in grouped_golfers_last_8 if col not in cols_to_move ] grouped_golfers_last_8 = grouped_golfers_last_8[cols].sort_values( by=['points_next_event'], ascending=False) st.write('Average Pts for last 8 events', grouped_golfers_last_8) gb = GridOptionsBuilder.from_dataframe(grouped_golfers_last_8) gb.configure_column( "total_points", type=["numericColumn", "numberColumnFilter", "customNumericFormat"], precision=0, aggFunc='sum') gb.configure_column( "avg_points", type=["numericColumn", "numberColumnFilter", "customNumericFormat"], precision=0, aggFunc='sum') gb.configure_column( "exp_points", type=["numericColumn", "numberColumnFilter", "customNumericFormat"], precision=0, aggFunc='sum')
def main(): st.markdown(""" <style> #MainMenu {visibility: hidden;} footer {visibility: hidden;} </style> """, unsafe_allow_html=True) padding = 0 st.markdown(f""" <style> .reportview-container .main .block-container{{ padding-top: {padding}rem; padding-right: {padding}rem; padding-left: {padding}rem; padding-bottom: {padding}rem; }} </style> """, unsafe_allow_html=True) COLOR = "black" BACKGROUND_COLOR = "#fff" max_width = 860 padding_top = 0 padding_right = 0 padding_left = 0 padding_bottom = 0 dj_contents = dj_soup.select(".prof dl") for i, element in enumerate(dj_contents): dj_ids.append(element.select('dt')[0]['id']) dj_images_urls.append(element.select('dt')[0].select('img')[0]['src']) dj_href = element.select('a')[0]['href'] if '/programs/' in dj_href: dj_hrefs.append(domain + dj_href) else: dj_hrefs.append(dj_href) el2 = dj_contents[i].get_text().split('\n')[1:-1] key = el2[0].split(':')[1] # -- dj_otherDicts = dict() #init for j in el2[1:]: key2 = j.split(':')[0] value = j.split(':')[1] dj_otherDicts.update({key2: value}) one_dict = {key: dj_otherDicts} dj_dicts.update(one_dict) for element in dj_contents: el1 = element.get_text().split('\n')[1:-1] name = el1[0].split(':')[1] dj_names.append(name) # -- 担当番組Program contents = dj_dicts[name] if '担当番組' in contents: dj_haveprograms.append(contents['担当番組']) else: dj_haveprograms.append('') # -- 誕生日Birth if '誕生日' in contents: dj_births.append(contents['誕生日']) else: dj_births.append('') # -- 血液型Blood if '血液型' in contents: dj_bloods.append(contents['血液型']) else: dj_bloods.append('') # -- 身長Hight if '身長' in contents: dj_heights.append(contents['身長']) else: dj_heights.append('') # -- 趣味Hobbys if '趣味' in contents: dj_hobbys.append(contents['趣味']) else: dj_hobbys.append('') # -- 特技Skills if '特技' in contents: dj_skills.append(contents['特技']) else: dj_skills.append('') df = pd.DataFrame({ 'id': dj_ids, '名前Name': dj_names, '担当番組Program': dj_haveprograms, '誕生日Birth': dj_births, '血液型Blood': dj_bloods, '身長Hight': dj_heights, '趣味Hobbys': dj_hobbys, '特技Skills': dj_skills, '画像URL': dj_images_urls }) # df.index = np.arange(1, len(df)+1) for cnt, entrie in enumerate(program_res.entries): #program_id = entrie['mobileimg']['src'].split('/')[5] #bad error 2021/11/05 program_id = entrie['link'].split('/')[5] #new 2021/11/05 mark = "/" + program_id + "/" href = entrie['links'][1]['href'] program_ids.append(program_id) program_titles.append(str(cnt + 1) + ": " + entrie['title']) program_subtitles.append(entrie['mobilesubtitle']) program_image_urls.append(entrie['mobileimg']['src']) program_summarys.append(entrie['summary']) program_sound_urls.append(program_base + mark + href) datestr = entrie['published'] program_pubdates.append( datetime.datetime.strptime( datestr, '%a, %d %b %Y %H:%M:%S %z').strftime('%Y/%m/%d')) program_djnames.append(' ') program_sound_times.append(' ') # program_djnames 追加 for i, dj_id in enumerate(program_ids): if dj_id in dj_ids: program_djnames[i] = dj_names[dj_ids.index(dj_id)] else: program_djnames[i] = '' df2 = pd.DataFrame({ 'id': program_ids, 'Program': program_titles, '番組名': program_subtitles, 'DJName': program_djnames, '配信日Pubday': program_pubdates, '再生時間SoundTime': program_sound_times }) # df.index = np.arange(1, len(df)+1) st.title("RADIO365 DJ's Fan site") hedder_text = f"""Obtained automatically from [RADIO365](https://www.radio365.net/). [update:2021/11/06]<br> Click the Play button below the image to play the program. (Please pay attention to the audio)<br> You can also use the upper left select box to switch programs (from 1 to 100).<br> [RADIO365](https://www.radio365.net/)から自動取得しています。<br> 画像の下にある再生ボタンで番組が再生されます。(音声にご注意ください)<br> 左上セレクトボックスでも番組(1~100迄)切替ができます。 """ st.markdown(hedder_text, unsafe_allow_html=True) selector = st.sidebar.selectbox("Select program (1 - 100):", program_titles) select_indexNumber = int(selector.split(':')[0]) - 1 # dark_theme = st.sidebar.checkbox("Dark Theme", False) # if dark_theme: # BACKGROUND_COLOR = "rgb(17,17,17)" # COLOR = "#fff" st.markdown( f""" <style> .reportview-container .main .block-container{{ max-width: {max_width}px; # padding-top: {padding_top}rem; # padding-right: {padding_right}rem; # padding-left: {padding_left}rem; # padding-bottom: {padding_bottom}rem; }} # .reportview-container .main {{ # color: {COLOR}; # background-color: {BACKGROUND_COLOR}; # }} # h1 {{ # color: {COLOR}; # background-color: {BACKGROUND_COLOR}; # }} # h5 {{ # color: {COLOR}; # background-color: {BACKGROUND_COLOR}; # }} # .css-145kmo2 {{ # color: {COLOR}; # background-color: {BACKGROUND_COLOR}; # }} # .css-qbe2hs {{ # color: {COLOR}; # background-color: {BACKGROUND_COLOR}; # }} # .st-ck {{ # color: {COLOR}; # background-color: {BACKGROUND_COLOR}; # }} # .css-xq1lnh-EmotionIconBase {{ # color: {COLOR}; # background-color: {BACKGROUND_COLOR}; # }} </style> """, unsafe_allow_html=True, ) markdown_str = "#### " + '<font color="Gray">' + program_subtitles[ select_indexNumber] + '</font>' st.markdown(markdown_str, unsafe_allow_html=True) #===== read sidebar image file ======= img_data = read_image(program_image_urls[select_indexNumber]) st.image(img_data, caption=selector, use_column_width=True) # sound update sound_data = read_sound_data(program_sound_urls[select_indexNumber]) st.audio(sound_data, format='audio/aac') st.markdown(program_summarys[select_indexNumber], unsafe_allow_html=True) st.write('') # DJ photo & profile block htmls = set_hrefs(dj_hrefs) html_height = (int(len(htmls) / 8) + 1) * 62 joinhtml = "".join(htmls) html = f"""{joinhtml}""" with st.expander("DJ Photo (please click to see phot & profile)", expanded=True): componentsv1.html(html, height=html_height, scrolling=True) st.sidebar.text('') # Sidebar DJ photo temp_text = str(len(dj_images_urls)) + " DJ member:" st.sidebar.text(temp_text) dj_img_datas = read_sidebar_photos() for i, dj_image_url in enumerate(dj_images_urls): st.sidebar.image(dj_img_datas[i], caption=dj_names[i], use_column_width='True') # for i, program_sound_url in enumerate(program_sound_urls): # sound_data = read_sound_data(program_sound_urls[i]) # program_sound_times[i] = get_sound_time(program_sound_urls[i], sound_data) # DJ List with st.expander("DJ List (please click to see dj list)", expanded=True): #customize gridOptions gb = GridOptionsBuilder.from_dataframe(df) gb.configure_grid_options( pagination=True, paginationAutoPageSize=True, ) gridOptions = gb.build() AgGrid(df, autosize=True, gridOptions=gridOptions) st.markdown(get_table_download_link(df), unsafe_allow_html=True) # Program List with st.expander('Program List (please click to see program list)', expanded=True): gb2 = GridOptionsBuilder.from_dataframe(df2) gb2.configure_grid_options( pagination=True, paginationAutoPageSize=True, ) gridOptions2 = gb2.build() AgGrid(df2, autosize=True, gridOptions=gridOptions2) st.markdown(get_table_download_link(df2), unsafe_allow_html=True)
def app(): st.markdown("## Timestamped Corpus") if st.session_state.metadata: kiara = st.session_state["kiara"] augmented_table_value = st.session_state.augmented_data sql_query_day = "SELECT strptime(concat(day, '/', month, '/', year), '%d/%m/%Y') as date, pub_name, count FROM (SELECT YEAR(date) as year, MONTH(date) as month, DAY(date) as day, pub_name, count(*) as count FROM data group by YEAR(date), MONTH(date), DAY(date), pub_name ORDER BY year, month, day, pub_name) as agg" sql_query_month = "SELECT strptime(concat('01/', month, '/', year), '%d/%m/%Y') as date, pub_name, count FROM (SELECT YEAR(date) as year, MONTH(date) as month, pub_name, count(*) as count FROM data group by YEAR(date), MONTH(date), pub_name ORDER BY year, month, pub_name) AS agg" sql_query_year = "SELECT strptime(concat('01/01/', year), '%d/%m/%Y') as date, pub_name, count FROM (SELECT YEAR(date) as year, pub_name, count(*) as count FROM data group by YEAR(date), pub_name ORDER BY year, pub_name) AS agg" my_expander = st.sidebar.expander(label='Settings') with my_expander: unit = st.selectbox("Aggregate by", ('year', 'month', 'day')) scaleType = st.selectbox("Scale by", ('color', 'height')) axisLabel = st.selectbox("Axis", ('5-year', 'year', 'month', 'day')) if unit == "day": query = sql_query_day elif unit == "month": query = sql_query_month else: query = sql_query_year query_workflow = kiara.create_workflow("table.query.sql") query_workflow.inputs.set_values(table=augmented_table_value, query=query) query_result_value = query_workflow.outputs.get_value_obj( "query_result") query_result_table = query_result_value.get_value_data() data = list( query_result_table.to_pandas().to_dict(orient="index").values()) data_json = json.dumps(data, default=str) cleaned_data = json.loads(data_json) observers = observable("Test", notebook="d/d1e17c291019759e", targets=["viewof chart", "style"], redefine={ "timeSelected": unit, "data": cleaned_data, "scaleType": scaleType, "axisLabel": axisLabel }, observe=["dateInfo"]) timeInfo = observers.get("dateInfo") col1, col2 = st.columns(2) if "preview_choice" not in st.session_state: st.session_state.preview_choice = "data" with col1: data_preview = st.button(label='Aggregated data') with col2: source_view = st.button(label='Sources list by time period') if data_preview: st.session_state.preview_choice = "data" if source_view: st.session_state.preview_choice = "source" display_choice = st.session_state.preview_choice if display_choice == "data": AgGrid(query_result_table.to_pandas()) else: if timeInfo is None: st.markdown( 'Hover over chart and click on date that appears on top') if timeInfo is not None: sql_query_day2 = f"SELECT pub_name, date, content FROM data WHERE DATE_PART('year', date) = {timeInfo[0]} AND DATE_PART('month', date) = {timeInfo[1]} and DATE_PART('day', date) = {timeInfo[2]}" sql_query_month2 = f"SELECT pub_name, date, content FROM data WHERE DATE_PART('year', date) = {timeInfo[0]} AND DATE_PART('month', date) = {timeInfo[1]}" sql_query_year2 = f"SELECT pub_name, date, content FROM data WHERE DATE_PART('year', date) = {timeInfo[0]}" if unit == "day": query2 = sql_query_day2 elif unit == "month": query2 = sql_query_month2 else: query2 = sql_query_year2 query_workflow2 = kiara.create_workflow("table.query.sql") query_workflow2.inputs.set_values(table=augmented_table_value, query=query2) query_result_value2 = query_workflow2.outputs.get_value_obj( "query_result") query_result_table2 = query_result_value2.get_value_data() df2 = query_result_table2.to_pandas() gb = GridOptionsBuilder.from_dataframe(df2) gb.configure_column("content", maxWidth=800, tooltipField="content") AgGrid(df2.head(100), gridOptions=gb.build()) else: st.write( "This optional step is only activated if your corpus files contain dates. Please go to the next step." )
import pandas as pd from st_aggrid import AgGrid, DataReturnMode, GridUpdateMode, GridOptionsBuilder, JsCode, grid_options_builder @st.cache() def get_data(multiindex=False): df = pd.DataFrame( np.random.randint(0, 100, 100).reshape(-1, 5), columns=list("abcde"), index=pd.MultiIndex.from_product( [list("xyzw"), list("12345")]) if multiindex else None) return df multiindex = st.sidebar.checkbox("Create a Multindexed DataFrame", False) data = get_data(multiindex) #converts the multi index to a . separated string :) if multiindex: data.index = [".".join(t) for t in data.index] data = data.reset_index() gb = GridOptionsBuilder.from_dataframe(data, minWidth=150) gb.configure_first_column_as_index() go = gb.build() AgGrid(data, go, enable_enterprise_modules=True, fit_columns_on_grid_load=False)
def main(): # オブジェクトを毎回読み込みを避けるため if 'robot' not in st.session_state: st.session_state['robot'] = bcap_robot() if 'start_flg' not in st.session_state: st.session_state['start_flg'] = False # End if st.title('ロボットコントローラボード') st.sidebar.header('接続先のロボットのIPアドレスを入力してください') # テキスト入力 ip_add_str = st.sidebar.text_input('IPアドレス', '192.168.0.1') # ボタン start_button = st.sidebar.empty() select_boad_type = st.sidebar.radio('モードを選択してください。', ('robot_control', 'program_edit', 'variable_edit', 'position_monitor')) if not st.session_state['start_flg']: st.session_state['start_flg'] = start_button.button('Start', key='start') else: st.session_state['start_flg'] = not(start_button.button('Stop', key='start')) if st.session_state['start_flg']: res = st.session_state['robot'].connect(ip_add_str, 5007) st.write(res) # markdown st.subheader('接続先ロボット情報') # サブヘッダー ret_DataFrame = st.session_state['robot'].get_base_information() st.table(ret_DataFrame) if select_boad_type == 'robot_control': st.subheader('ロボットを操作します。') ret_ext_val = st.session_state['robot'].get_extSpeed() ExtSpeed = st.slider(label='extenal Speed', min_value=0.1, max_value=100.0, value=ret_ext_val) st.session_state['robot'].set_extSpeed(ExtSpeed) colA, colB = st.columns(2) with colA: control_mode_list = ['各軸', 'X-Y', 'Tool'] control_mode = st.selectbox('動作モード', control_mode_list) with colB: dist_len = 0.0 dist_len = st.number_input('動作距離', 0.0, 10.0, 0.0, step=0.1) move_label = [] move_flg = [0, 0, 0, 0, 0, 0] if control_mode == '各軸': move_label = ['J' + str(i) for i in range(1, 7)] else: move_label = ['X', 'Y', 'Z', 'Rx', 'Ry', 'Rz'] # End if # カラムを追加する col1, col2, col3 = st.columns(3) with col1: for i in range(6): if st.button('-' + str(move_label[i]), key='m_' + str(i)): move_flg[i] -= 1 with col2: for i in range(6): st.text(' ' + str(move_label[i]) + ' ') with col3: for i in range(6): if st.button('+' + str(move_label[i]), key='p_' + str(i)): move_flg[i] += 1 if sum(move_flg) != 0: st.session_state['robot'].move_func(control_mode, dist_len, move_flg) elif select_boad_type == 'program_edit': select_program = '' select_list_programs = st.session_state['robot'].get_tasknames() select_program = st.selectbox('編集するプログラムを選択する', select_list_programs) if select_program != '': ret_file_val = st.session_state['robot'].get_file_value(select_program + '.pcs') new_text = st.text_area('Ctrl + Enter でコントローラへ書き込みます。', height=300, value=ret_file_val) st.session_state['robot'].rewrite_file_value(select_program + '.pcs', new_text) elif select_boad_type == 'variable_edit': select_list_variable = ['I', 'F', 'D', 'V', 'P', 'J', 'T', 'S'] select_variable = st.sidebar.selectbox('編集する', select_list_variable) val_len = st.session_state['robot'].get_value_len(select_variable) val_data = [] val_index = [] val_columns = [] if select_variable == 'V': val_columns = ['X', 'Y', 'Z', 'Use'] elif select_variable == 'P': val_columns = ['X', 'Y', 'Z', 'Rx', 'Ry', 'Rz', 'Fig', 'Use'] elif select_variable == 'J': val_columns = ['J1', 'J2', 'J3', 'J4', 'J5', 'J6', 'J7', 'J8', 'Use'] elif select_variable == 'T': val_columns = ['X', 'Y', 'Z', 'Ox', 'Oy', 'Oz', 'Ax', 'Ay', 'Az', 'Fig', 'Use'] else: val_columns = ['value', 'Use'] # End if for index in range(val_len): data = st.session_state['robot'].get_value(select_variable, index) if type(data) is list: val_data.append(data + ['']) else: val_data.append([data, '']) val_index.append(select_variable + str(index)) df = pd.DataFrame(val_data, index=val_index, columns=val_columns) # End for # st.write(df) # st.table(df) gb = GridOptionsBuilder.from_dataframe(df, editable=True) grid = AgGrid(df, gridOptions=gb.build(), fit_columns_on_grid_load=True, updateMode=GridUpdateMode.VALUE_CHANGED) # 修正が反映される st.dataframe(grid['data']) if st.button('Write', key='Write to controller variable'): write_count = st.empty() bar = st.progress(0) max_len = len(grid['data'].values.tolist()) for i, data in enumerate(grid['data'].values.tolist()): if(len(data) == 2): new_val = data[0] else: new_val = data[:-1] # End if st.session_state['robot'].put_value(select_variable, i, new_val) write_count.text(f'count {i + 1}') bar.progress((i + 1) / max_len) # End for st.write('write') # End if elif select_boad_type == 'position_monitor': count = 0 t = [] x = [] y = [] z = [] rx = [] ry = [] rz = [] # グラフを書き出すためのプレースホルダを用意する plot_area = st.empty() fig, axes = plt.subplots(3, 2) if st.button('Stop', key='stop'): pass while True: # 現在のグラフを消去する for i in (0, 1, 2): for j in (0, 1): axes[i][j].clear() # End for # End for # データを追加する pos_list = st.session_state['robot'].get_curpos() count = count + 1 t.append(count) x.append(pos_list[0]) y.append(pos_list[1]) z.append(pos_list[2]) rx.append(pos_list[3]) ry.append(pos_list[4]) rz.append(pos_list[5]) axes[0][0].plot(t, x, color='black') axes[1][0].plot(t, y, color='black') axes[2][0].plot(t, z, color='black') axes[0][1].plot(t, rx, color='black') axes[1][1].plot(t, ry, color='black') axes[2][1].plot(t, rz, color='black') # 100個以上のデータは削除する (FIFO) if len(t) >= 100: del t[0] del x[0] del y[0] del z[0] del rx[0] del ry[0] del rz[0] # プレースホルダに書き出す plot_area.pyplot(fig) time.sleep(0.01) # End while else: pass