Best Python code snippet using pyatom_python
AXClasses.py
Source:AXClasses.py  
...1125        return self._convenienceMatchR('AXRow', 'AXTitle', match)1126    def sliders(self, match=None):1127        """Return a list of sliders with an optional match parameter."""1128        return self._convenienceMatch('AXSlider', 'AXValue', match)1129    def slidersR(self, match=None):1130        """Return a list of sliders with an optional match parameter."""...main.py
Source:main.py  
1import dash_bootstrap_components as dbc2import dash_core_components as dcc3import dash_html_components as html4from dash.dependencies import Input, Output, State, MATCH, ALL5import dash_apps.shared_components as dsc6from dash_apps.shared_styles import *7from dash_apps.apps.myapp import app8import dash9from engine import Model, Simulator10import os11import plotly.express as px12import pandas as pd13path = os.getcwd()14# get all models in the models directory, skip penicilin15model_names = [o for o in sorted(os.listdir(os.path.join('rms','models'))) if os.path.isdir(os.path.join('rms','models',o))]16model_names.remove('penicillin_goldrick_2017')17model_path = lambda model_name: os.path.join(path,'rms','models', model_name) 18# make a Dropdown Menu to select a models19dropdown_models = lambda pick: [dbc.DropdownMenuItem(m, id = m, active = True) if i is pick else dbc.DropdownMenuItem(m, id = m,  active = False) for i,m in enumerate(model_names)]20def sim(model_name):21    """22    Generates simulator object based on model name23    Arguments24    ---------25        model_name26    """27    global mysim, mymvars, mycvars, mymparams, mysparams, data28    mysim = Simulator(model = Model(model_path(model_name)))29    mymvars = mysim.model.mvars.default30    try:31        mycvars = mysim.subroutines.subrvars.default32    except Exception as e:33        print(e)34        mycvars = None35    mymparams = mysim.model.params.default36    mysparams = mysim.simvars.default37    mysim.set_inputs()38    data = mysim.run()39    mymvars = mysim.model.reset()40    return 41def sliders_from_df(vars_df):42    """43    Generates sliders based on the variables in a DataFrame44    Arguments45    ---------46        vars_df: Pandas DataFrame containing variables47    """ 48    sliders = []49    if vars_df is not None:50        for i,var in enumerate(vars_df.index):51            try:52                if vars_df.loc[var,'Min'] is not False:53                    minval = vars_df.loc[var,'Min']54                else:55                    minval = vars_df.loc[var,'Value']*0.156                if vars_df.loc[var,'Max'] is not False:57                    maxval = vars_df.loc[var,'Max']58                else:59                    maxval = vars_df.loc[var,'Value']*1.960                slider = dsc.NamedSlider(61                            name= vars_df.loc[var,'Label'],62                            id={'type':'dynamic-var',63                                'index': var64                            },65                            min=minval,66                            max=maxval,67                            step=(maxval-minval)/100,68                            value = vars_df.loc[var,'Value'],69                            other = {'units':vars_df.loc[var,'Units'],'type':'slider-input'}70                        )71            except:72                try:73                    other = {'units':vars_df.loc[var,'Units'],'type':'just-input'}74                except:75                    other = {'type':'just-input'}76                slider = dsc.NamedSlider(77                            name= vars_df.loc[var,'Label'],78                            id={'type':'dynamic-var',79                                'index': var80                            },81                            value = vars_df.loc[var,'Value'],82                            other = other83                        )84            sliders.append(slider)85    return sliders86# make a diagram, if any87diagram = lambda simulator: dbc.Card(88    [89        dbc.CardImg(src=simulator.model.diagram, top=True, alt = 'Oh snap! No diagram for this model!'),90        dbc.CardBody(91            html.P(simulator.model.doc, className="card-text")92        ),93    ],94)95# make a button to run the simulator96run_btn = dbc.Button(children = "Run Simulation", outline=True, size = "lg", color="primary", className="mb-3", id="btn_run", n_clicks = 0)97# make a button for plots98plot_btn = dbc.Button(children = "Add Chart", outline=True, size = "lg", color="primary", className="mb-3", id="btn_plot", n_clicks = 0)99# layout all the components to be displayed100content = html.Div(101    [102        dbc.Row([103            dbc.Col(html.H1(children='Reactor Modeling Sandbox'), width = 9),104        ]),105        dbc.Row([106            dbc.Col(html.H5(children='Beep bop'), width = 9),107            dbc.Col(108                dbc.DropdownMenu(109                    label = "Select a model",110                    children = dropdown_models(0),111                    right=False,112                    id = 'dd_models'113                ),114            )115        ]),116        dbc.Row([117            dbc.Col(html.H1(children=''), width = 12),118        ]),119        dbc.Row([120            dbc.Col(dbc.Col([121                dbc.Row(dsc.collapse([], 'Manipulated Variables', 'mvars-collapse')),122                dbc.Row(dsc.collapse([], 'Control Variables', 'cvars-collapse')),123            ],124                id = 'slidersL'),width = 2),125            dbc.Col([],id = 'diagram1', width = 6),126            dbc.Col([127                dbc.Row(dsc.collapse([], 'Model Parameters', 'mparams-collapse')),128                dbc.Row(dsc.collapse([], 'Simulation Settings', 'sparams-collapse')),129            ],130                id = 'slidersR', width = 4),131        ]),132        dbc.Row(dbc.Col(run_btn)),133        dbc.Row(dbc.Col(plot_btn)),134        dbc.Row(id = 'container', children = []),135    ],136    id="page-content",137    style = CONTENT_STYLE138)139#Layout includes a button simulate, a button to add charts, and an empty list to add graphs.140layout = html.Div(141    [142        content,143        html.Div(id='dummy-output4'),144        html.Div(id='dummy-output-models')145    ],146)147# callback to update the simulator with the selected model148@app.callback(149    [Output("dd_models", "children")],150    [Output(s+"-collapse", "children") for s in ['mvars','cvars','mparams','sparams']],151    [Output('dummy-output-models','children')],152    [Output('diagram1','children')],153    [Input(m, "n_clicks") for m in model_names],154)155def update_simulator(*args):156    ctx = dash.callback_context157    # this gets the id of the button that triggered the callback158    button_id = ctx.triggered[0]["prop_id"].split(".")[0]159    try:160        new_pick = model_names.index(button_id)161    except:162        new_pick = 0163    sim(model_names[new_pick])164    return dropdown_models(new_pick), sliders_from_df(mymvars[~mymvars.State]), *[sliders_from_df(p) for p in [mycvars, mymparams, mysparams]], [], diagram(mysim)165# callback to update the model variables with the sliders / input box166@app.callback(167    [Output({'type': 'dynamic-var-input', 'index': ALL}, 'value'),168    Output({'type': 'dynamic-var', 'index': ALL}, 'value')],169    [Input({'type': 'dynamic-var-input', 'index': ALL}, 'value'),170    Input({'type': 'dynamic-var', 'index': ALL}, 'value')]171)172def update_mvars_slider(inputs,sliders):173    ctx = dash.callback_context174    button_id = ctx.triggered[0]['prop_id'].split('.')[0]175    if button_id:176        if 'input' in button_id:177            sliders = inputs[:len(sliders)]178        else:179            inputs[:len(sliders)] = sliders180        l1 = len(mysim.model.mvars.from_input['Value']) # cheap but works181        try:182            l2 = len(mysim.subroutines.subrvars.from_input['Value'])+l1183        except:184            l2 = l1185        l3 = len(mysim.model.params.from_input['Value'])+l2186        mysim.model.mvars.from_input['Value'].iloc[:] = inputs[:l1]187        try:188            mysim.subroutines.subrvars.from_input['Value'].iloc[:] = inputs[l1:l2]189        except:190            pass191        mysim.model.params.from_input['Value'].iloc[:] = inputs[l2:l3]192        mysim.simvars.from_input['Value'].iloc[:] = inputs[l3:]193    return inputs, sliders194# callback to run the simulator and display data when the button is clicked195@app.callback(196    Output('dummy-output4','children'),197    Input('btn_run', 'n_clicks'),198)199def run_simulation(n_clicks_run):200    if n_clicks_run>0:201        global data, mymvars202        mysim.set_inputs()203        data = mysim.run()204        mymvars = mysim.model.reset()205    return206   207# Takes the n-clicks of the add-chart button and the state of the container children.208@app.callback(209   Output('container','children'),210   [Input('btn_plot','n_clicks'),211   Input('dummy-output4','children'),212   Input('dummy-output-models','children')],213   [State('btn_run','n_clicks'),214   State('container','children')]215)216#This function is triggered when the add-chart clicks changes. This function is not triggered by changes in the state of the container. If children changes, state saves the change in the callback.217def display_graphs(n_clicks, dummy,dummy_models, n_run, div_children):218    ctx = dash.callback_context219    button_id = ctx.triggered[0]["prop_id"].split(".")[0]220    if button_id == 'dummy-output-models':221        div_children = []222    elif button_id == 'btn_plot' or (n_clicks == 0 and n_run == 0):223        new_child = dbc.Col(224            children=[225                dbc.Row([226                dbc.Col(dbc.RadioItems(227                    id={'type':'dynamic-choice',228                        'index':n_clicks229                    },230                    options=[{'label': 'Line Chart', 'value': 'line'},231                            {'label':'Bar Chart', 'value': 'bar'}232                            ],233                    value='line',234                ), width = 2),235                dbc.Col(dcc.Dropdown(236                    id={237                        'type': 'dynamic-dpn-var1',238                        'index': n_clicks239                    },240                    options=[{'label': pd.concat([mymvars,mycvars]).loc[var,'Label'] + ' ('+var+')', 'value': var} for var in data.columns[data.columns.map(lambda x: '0' not in x)]],241                    multi=True,242                    value = [],243                    placeholder='Select variables to plot...',244                    clearable=False245                ), width = 8),246                dbc.Col([247                    dbc.Label('Time'),248                    dcc.Slider(249                    id={'type':'dynamic-slider',250                        'index':n_clicks251                    },252                    min=1,253                    max=len(mysim.time)-1,254                    step=1,255                    value=len(mysim.time)-1,256                )], width = 2),257                ]),258                dcc.Graph(259                    id={260                        'type':'dynamic-graph',261                        'index':n_clicks262                    },263                    figure={}264                ),265            ],266        width = 4)267        div_children.append(new_child)268    elif button_id == 'dummy-output4':269        for c,child in enumerate(div_children):270            try:271                for l,line in enumerate(child['props']['children'][1]['props']['figure']['data']):272                    old_data = div_children[c]['props']['children'][1]['props']['figure']['data'][l]['y']273                    var = div_children[c]['props']['children'][1]['props']['figure']['data'][l]['legendgroup']274                    div_children[c]['props']['children'][1]['props']['figure']['data'][l]['y'] = data[var].iloc[:len(old_data)].tolist()275            except:276                pass277    return div_children278# callback to update the graphs with the selected variables and graph types279@app.callback(280    Output({'type': 'dynamic-graph', 'index': MATCH}, 'figure'),281    [Input(component_id={'type': 'dynamic-dpn-var1', 'index': MATCH}, component_property='value'),282     Input(component_id={'type': 'dynamic-choice', 'index': MATCH}, component_property='value'),283     Input(component_id={'type': 'dynamic-slider', 'index': MATCH}, component_property='value')],284     State({'type': 'dynamic-graph', 'index': MATCH}, 'figure')285)286def new_graph(var, chart_type, time_idx, old_fig):287    ctx = dash.callback_context288    global data289    data = data.astype(float)290    if ctx.triggered[0]["prop_id"] != '.':291        if len(var) == 0:292            fig = old_fig293        else:294            if chart_type == 'bar':295                fig = px.bar(x = var, y= data[var].iloc[time_idx], color=var, labels = {'y':'Value at {:.2f}'.format(data.index[time_idx]), 'x':'Variable', 'color':'Variable'})296            elif chart_type == 'line':297                fig = px.line(data.iloc[:time_idx] , x = data.iloc[:time_idx].index, y = var, labels = {'x':'Time','value':'Value', 'variable':'Variable'})298            fig.update_layout(legend_orientation='h')                299            # change labels300            labels = {v: pd.concat([mymvars,mycvars]).loc[v,'Label'] + ' (' + pd.concat([mymvars,mycvars]).loc[v,'Units'] +')' for v in var}301            for i, dat in enumerate(fig.data):302                for elem in dat:303                    if elem == 'name':304                        fig.data[i].name = labels[fig.data[i].name]305        return fig306    else:307        return old_fig308# callback to collapse the different slider menus309@app.callback(310    [Output(s+"-collapse", "is_open") for s in ['mvars','cvars','mparams','sparams']],311    [Input(s+"-collapse-button", "n_clicks") for s in ['mvars','cvars','mparams','sparams']],312    [State(s+"-collapse", "is_open") for s in ['mvars','cvars','mparams','sparams']],313)314def toggle_collapse(*args):315    are_open = list(args[int(len(args)/2):])316    ns = list(args[:int(len(args)/2)])317    ctx = dash.callback_context318    button_id = ctx.triggered[0]['prop_id'].split('.')[0]319 320    for i,n in enumerate(['mvars','cvars','mparams','sparams']):321        if n in button_id:322            are_open[i] = not are_open[i]...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
