예제 #1
0
def ediss(b):
    result = 'E = 0 J'
    st.latex(r"E = R I^2 \Delta t")
    if b == "Energia Dissipada (J)":
        result = 'E = 0 J'
        e = ""
        r = st.number_input("Resistência (Ω)", format="%g", step=1.0)
        i = st.number_input("Corrente Elétrica (A)", format="%g", step=1.0)
        t = st.number_input("Variação do Tempo (s)", format="%g", step=1.0)
    elif b == "Resistência (Ω)":
        result = "R = 0 Ω"
        e = st.number_input("Energia Dissipada (J)", format="%g", step=1.0)
        r = ""
        i = st.number_input("Corrente Elétrica (A)", format="%g", step=1.0)
        t = st.number_input("Variação do Tempo (s)", format="%g", step=1.0)
    elif b == "Corrente Elétrica (A)":
        result = "I = 0 A"
        e = st.number_input("Energia Dissipada (J)", format="%g", step=1.0)
        r = st.number_input("Resistência (Ω)", format="%g", step=1.0)
        i = ""
        t = st.number_input("Variação do Tempo (s)", format="%g", step=1.0)
    elif b == "Variação do Tempo (s)":
        result = f'Δt = 0 s'
        e = st.number_input("Energia Dissipada (J)", format="%g", step=1.0)
        r = st.number_input("Resistência (Ω)", format="%g", step=1.0)
        i = st.number_input("Corrente Elétrica (A)", format="%g", step=1.0)
        t = ""
    if st.button("Calcular"):
        result = calc(e, r, i, t)
    st.title(result)
예제 #2
0
def am(b):
    result = 'a = 0 m/s²'
    st.latex(r"a = \frac{\Delta v}{\Delta t}")
    if b == "Aceleração Centrípeta (m/s²)":
        result = 'ac = 0 m/s²'
        a = ""
        v = st.number_input("Variação da Velocidade (m/s)",
                            format="%g",
                            step=1.0)
        t = st.number_input("Variação do Tempo (s)", format="%g", step=1.0)
    elif b == "Variação da Velocidade (m/s)":
        result = "Δv = 0 m/s"
        a = st.number_input("Aceleração Centrípeta (m/s²)",
                            format="%g",
                            step=1.0)
        v = ""
        t = st.number_input("Variação do Tempo (s)", format="%g", step=1.0)
    elif b == "Variação do Tempo (s)":
        result = "Δt = 0 s"
        a = st.number_input("Aceleração Centrípeta (m/s²)",
                            format="%g",
                            step=1.0)
        v = st.number_input("Variação da Velocidade (m/s)",
                            format="%g",
                            step=1.0)
        t = ""
    if st.button("Calcular"):
        result = calc(a, v, t)
    st.title(result)
예제 #3
0
def eqv(b):
    result = 'v = 0 m/s'
    st.latex(r"v(t) = v_0 + a t")
    if b == "Velocidade (m/s)":
        result = 'v = 0 m/s'
        v = ""
        v0 = st.number_input("Velocidade inicial (m/s)", format="%g" , step=1.0)
        a = st.number_input("Aceleração (m/s²)", format="%g" , step=1.0)
        t = st.number_input("Tempo (s)", format="%g" , step=1.0)
    elif b == "Velocidade inicial (m/s)":
        result = 'v₀ = 0 m/s'
        v = st.number_input("Velocidade (m/s)", format="%g" , step=1.0)
        v0 = ""
        a = st.number_input("Aceleração (m/s²)", format="%g" , step=1.0)
        t = st.number_input("Tempo (s)", format="%g" , step=1.0)
    elif b == "Aceleração (m/s²)":
        result = 'a = 0 m/s²'
        v = st.number_input("Velocidade (m/s)", format="%g" , step=1.0)
        v0 = st.number_input("Velocidade inicial (m/s)", format="%g" , step=1.0)
        a = ""
        t = st.number_input("Tempo (s)", format="%g" , step=1.0)
    elif b == "Tempo (s)":
        result = 't = 0 s'
        v = st.number_input("Velocidade (m/s)", format="%g" , step=1.0)
        v0 = st.number_input("Velocidade inicial (m/s)", format="%g" , step=1.0)
        a = st.number_input("Aceleração (m/s²)", format="%g" , step=1.0)
        t = ""
    if st.button("Calcular"):
         result = calc(v, v0, a, t)
    st.title(result)
예제 #4
0
def testText():
    import altair as alt
    # 显示固定宽度的格式化字符串
    st.text('This is some text.')
    # streamlit.markdown(body, unsafe_allow_html=False)
    # 以Markdown格式显示字符串
    st.markdown('Streamlit is **_really_ cool**.')
    # 以Latex格式显示公式
    st.latex(r'''
    a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
    \sum_{k=0}^{n-1} ar^k =
    a \left(\frac{1-r^{n}}{1-r}\right)
    ''')

    # streamlit.write(*args, **kwargs)
    # 显示参数到APP,瑞士军刀般的命令,几乎可以自动化输出任何类型的数据
    st.write('Hello, *World!* :sunglasses:')
    st.write(1234)
    st.write(
        pd.DataFrame({
            'first column': [1, 2, 3, 4],
            'second column': [10, 20, 30, 40],
        }))
    st.write('1 + 1 = ', 2)
    # 显示图表
    df = pd.DataFrame(np.random.randn(200, 3), columns=['a', 'b', 'c'])

    c = alt.Chart(df).mark_circle().encode(x='a', y='b', size='c', color='c')

    st.write(c)
    # streamlit.code(body, language='python')
    # 格式化显示代码
    code = '''def hello():
    print("Hello, Streamlit!")'''
    st.code(code, language='python')
예제 #5
0
def irrade(b):
    result = 'Er = 0 W/m²'
    st.latex(r"Er = \frac{E}{A \Delta t}")
    if b == "Irradiância (W/m²)":
        result = 'Er = 0 W/m²'
        e = ""
        p = st.number_input("Energia (J)", format="%g", step=1.0)
        a = st.number_input("Área (m²)", format="%g", step=1.0)
        t = st.number_input("Variação do Tempo (s)", format="%g", step=1.0)
    elif b == "Energia (J)":
        result = "E = 0 J"
        e = st.number_input("Irradiância (W/m²)", format="%g", step=1.0)
        p = ""
        a = st.number_input("Área (m²)", format="%g", step=1.0)
        t = st.number_input("Variação do Tempo (s)", format="%g", step=1.0)
    elif b == "Área (m²)":
        result = "A = 0 m²"
        e = st.number_input("Irradiância (W/m²)", format="%g", step=1.0)
        p = st.number_input("Energia (J)", format="%g", step=1.0)
        a = ""
        t = st.number_input("Variação do Tempo (s)", format="%g", step=1.0)
    elif b == "Variação do Tempo (s)":
        result = "Δt = 0 s"
        e = st.number_input("Irradiância (W/m²)", format="%g", step=1.0)
        p = st.number_input("Energia (J)", format="%g", step=1.0)
        a = st.number_input("Área (m²)", format="%g", step=1.0)
        t = ""
    if st.button("Calcular"):
        result = calc(e, p, a, t)
    st.title(result)
예제 #6
0
def snell(t):
    result = 'n1 = 0'
    u = st.radio("", ["Ângulo em graus", "Ângulo em radianos"])
    st.latex(r"n_1 \times sen(\alpha_1) = n_2 \times sen(\alpha_2)")
    if u == "Ângulo em graus":
        u = "º"
    else:
        u = "rad"
    if t == "Índice de refração 1":
        result = 'n1 = 0'
        n1 = ""
        sen1 = st.number_input(f"Ângulo α1 ({u})", format="%g", step=1.0)
        n2 = st.number_input("Índice de refração 2", format="%g", step=1.0)
        sen2 = st.number_input(f"Ângulo α2 ({u})", format="%g", step=1.0)
    elif t == "Ângulo α1":
        result = f'α1 = 0 {u}'
        n1 = st.number_input("Índice de refração 1", format="%g", step=1.0)
        sen1 = ""
        n2 = st.number_input("Índice de refração 2", format="%g", step=1.0)
        sen2 = st.number_input(f"Ângulo α ({u})", format="%g", step=1.0)
    elif t == "Índice de refração 2":
        result = 'n2 = 0'
        n1 = st.number_input("Índice de refração 1", format="%g", step=1.0)
        sen1 = st.number_input(f"Ângulo α1 ({u})", format="%g", step=1.0)
        n2 = ""
        sen2 = st.number_input(f"Ângulo α2 ({u})", format="%g", step=1.0)
    elif t == "Ângulo α2":
        result = f'α2 = 0 {u}'
        n1 = st.number_input("Índice de refração 1", format="%g", step=1.0)
        sen1 = st.number_input(f"Ângulo α1 ({u})", format="%g", step=1.0)
        n2 = st.number_input("Índice de refração 2", format="%g", step=1.0)
        sen2 = ""
    if st.button("Calcular"):
        result = calc(n1, sen1, n2, sen2)
    st.title(result)
예제 #7
0
def ac1(t):
    result = 'ac = 0 m/s²'
    st.latex(r"a_c = \frac{v^2}{R}")
    if t == "Aceleração Centrípeta (m/s²)":
        result = 'ac = 0 m/s²'
        a = ""
        v = st.number_input("Velocidade (m/s)", format="%g", step=1.0)
        r = st.number_input("Raio (m)", format="%g", step=1.0)
    elif t == "Velocidade (m/s)":
        result = "v = 0 m/s"
        a = st.number_input("Aceleração Centrípeta (m/s²)",
                            format="%g",
                            step=1.0)
        v = ""
        r = st.number_input("Raio (m)", format="%g", step=1.0)
    elif t == "Raio (m)":
        result = "R = 0 m"
        a = st.number_input("Aceleração Centrípeta (m/s²)",
                            format="%g",
                            step=1.0)
        v = st.number_input("Velocidade (m/s)", format="%g", step=1.0)
        r = ""
    if st.button("Calcular"):
        result = calc(a, v, r)
    st.title(result)
예제 #8
0
def fmag(t):
    result = 'ϕ = 0 Wb'
    u = st.radio("", ["Ângulo em graus", "Ângulo em radianos"])
    st.latex(r"\Phi = B  A  cos(\alpha)")
    if u == "Ângulo em graus":
        u = "º"
    else:
        u = "rad"
    if t == "Fluxo magnético (Wb)":
        result = 'ϕ = 0 Wb'
        f = ""
        b = st.number_input("Campo magnético (T)", format="%g", step=1.0)
        a = st.number_input("Área (m²)", format="%g", step=1.0)
        cos = st.number_input(f"Ângulo α ({u})", format="%g", step=1.0)
    elif t == "Campo magnético (T)":
        result = 'B = 0 T'
        f = st.number_input("Fluxo magnético (Wb)", format="%g", step=1.0)
        b = ""
        a = st.number_input("Área (m²)", format="%g", step=1.0)
        cos = st.number_input(f"Ângulo α ({u})", format="%g", step=1.0)
    elif t == "Área (m²)":
        result = 'A = 0 m²'
        f = st.number_input("Fluxo magnético (Wb)", format="%g", step=1.0)
        b = st.number_input("Campo magnético (T)", format="%g", step=1.0)
        a = ""
        cos = st.number_input(f"Ângulo α ({u})", format="%g", step=1.0)
    elif t == "Ângulo α":
        result = f'α = 0 {u}'
        f = st.number_input("Fluxo magnético (Wb)", format="%g", step=1.0)
        b = st.number_input("Campo magnético (T)", format="%g", step=1.0)
        a = st.number_input("Área (m²)", format="%g", step=1.0)
        cos = ""
    if st.button("Calcular"):
        result = calc(f, b, a, cos, u)
    st.title(result)
예제 #9
0
파일: fg.py 프로젝트: Force4760/fqhelperweb
def fg(t):
    result = 'F = 0 N'
    st.latex(r"F = G \frac{m_1 m_2}{R^2}")
    if t == "Força gravítica (N)":
        result = 'F = 0 N'
        f = ""
        m1 = st.number_input("Massa 1 (Kg)", format="%g" , step=1.0)
        m2 = st.number_input("Massa 2 (Kg)", format="%g" , step=1.0)
        r = st.number_input("Raio (m)", format="%g" , step=1.0)
    elif t == "Massa 1 (Kg)":
        result = "m1 = 0 Kg"
        f = st.number_input("Força gravítica (N)", format="%g" , step=1.0)
        m1 = ""
        m2 = st.number_input("Massa 2 (Kg)", format="%g" , step=1.0)
        r = st.number_input("Raio (m)", format="%g" , step=1.0)
    elif t == "Massa 2 (Kg)":
        result = "m2 = 0 Kg"
        f = st.number_input("Força gravítica (N)", format="%g" , step=1.0)
        m1 = st.number_input("Massa 1 (Kg)", format="%g" , step=1.0)
        m2 = ""
        r = st.number_input("Raio (m)", format="%g" , step=1.0)
    elif t == "Raio (m)":
        result = "R = 0 m"
        f = st.number_input("Força gravítica (N)", format="%g" , step=1.0)
        m1 = st.number_input("Massa 1 (Kg)", format="%g" , step=1.0)
        m2 = st.number_input("Massa 2 (Kg)", format="%g" , step=1.0)
        r = ""
    if st.button("Calcular"):
         result = calc(f, m1, m2, r)
    st.title(result)
예제 #10
0
def wfnc(t):
    result = 'Wfnc = 0 J'
    st.latex(r"W_{Fnc} = \Delta E_m")
    if t == "Trabalho das forças não conservativas (J)":
        result = 'Wfnc = 0 J'
        e = ""
        f = st.number_input("Energia mecânica final (J)",
                            format="%g",
                            step=1.0)
        i = st.number_input("Energia mecânica inicial (J)",
                            format="%g",
                            step=1.0)
    elif t == "Energia mecânica final (J)":
        result = "Emf = 0 J"
        f = ""
        e = st.number_input("Trabalho das forças não conservativas (J)",
                            format="%g",
                            step=1.0)
        i = st.number_input("Energia mecânica inicial (J)",
                            format="%g",
                            step=1.0)
    elif t == "Energia mecânica inicial (J)":
        result = "Emi = 0 J"
        i = ""
        e = st.number_input("Trabalho das forças não conservativas (J)",
                            format="%g",
                            step=1.0)
        f = st.number_input("Energia mecânica final (J)",
                            format="%g",
                            step=1.0)
    if st.button("Calcular"):
        result = calc(e, f, i)
    st.title(result)
예제 #11
0
def cm(t):
    result = 'cm = 0 g/dm³'
    st.latex(r"c_m = \frac{m}{V}")
    if t == "Concentração mássica (g/dm³)":
        result = 'cm = 0 g/dm³'
        cm = ""
        v = st.number_input("Volume (dm³)", format="%g", step=1.0)
        m = st.number_input("Massa (g)", format="%g", step=1.0)
    elif t == "Volume (dm³)":
        result = "V = 0 dm³"
        v = ""
        cm = st.number_input("Concentração mássica (g/dm³)",
                             format="%g",
                             step=1.0)
        m = st.number_input("Massa (g)", format="%g", step=1.0)
    elif t == "Massa (g)":
        result = "m = 0 g"
        m = ""
        cm = st.number_input("Concentração mássica (g/dm³)",
                             format="%g",
                             step=1.0)
        v = st.number_input("Volume (dm³)", format="%g", step=1.0)
    if st.button("Calcular"):
        result = calc(cm, m, v)
    st.title(result)
예제 #12
0
def putil(b):
    result = 'P = 0 W'
    st.latex(r"P = U I")
    if b == "Potência Útil (W)":
        result = 'P = 0 W'
        e = ""
        r = st.number_input("Diferença de Potencial (V)",
                            format="%g",
                            step=1.0)
        i = st.number_input("Corrente Elétrica (A)", format="%g", step=1.0)
    elif b == "Diferença de Potencial (V)":
        result = "U = 0 V"
        e = st.number_input("Potência Útil (W)", format="%g", step=1.0)
        r = ""
        i = st.number_input("Corrente Elétrica (A)", format="%g", step=1.0)
    elif b == "Corrente Elétrica (A)":
        result = "I = 0 A"
        e = st.number_input("Potência Útil (W)", format="%g", step=1.0)
        r = st.number_input("Diferença de Potencial (V)",
                            format="%g",
                            step=1.0)
        i = ""
    if st.button("Calcular"):
        result = calc(e, r, i)
    st.title(result)
예제 #13
0
파일: xa.py 프로젝트: Force4760/fqhelperweb
def xa(t):
    result = 'X = 0'
    st.latex(r"X = \frac{n_a}{n_t}")
    if t == "Fração molar":
        result = 'X = 0'
        xa = ""
        nt = st.number_input("Quantidade total (mol)", format="%g", step=1.0)
        na = st.number_input("Quantidade da amostra (mol)",
                             format="%g",
                             step=1.0)
    elif t == "Quantidade total (mol)":
        result = "nt = 0 mol"
        nt = ""
        xa = st.number_input("Fração molar", format="%g", step=1.0)
        na = st.number_input("Quantidade da amostra (mol)",
                             format="%g",
                             step=1.0)
    elif t == "Quantidade da amostra (mol)":
        result = "na = 0 mol"
        na = ""
        xa = st.number_input("Fração molar", format="%g", step=1.0)
        nt = st.number_input("Quantidade total (mol)", format="%g", step=1.0)
    if st.button("Calcular"):
        result = calc(xa, na, nt)
    st.title(result)
예제 #14
0
def v(b):
    result = 'v = 0 m/s'
    st.latex(r"v = \omega R")
    if b == "Velocidade (m/s)":
        result = 'v = 0 m/s'
        v = ""
        w = st.number_input("Velocidade Angular (rad/s)",
                            format="%g",
                            step=1.0)
        r = st.number_input("Raio (m)", format="%g", step=1.0)
    elif b == "Velocidade Angular (rad/s)":
        result = "ω = 0 rad/s"
        v = st.number_input("Velocidade (m/s)", format="%g", step=1.0)
        w = ""
        r = st.number_input("Raio (m)", format="%g", step=1.0)
    elif b == "Raio (m)":
        result = "R = 0 m"
        v = st.number_input("Velocidade (m/s)", format="%g", step=1.0)
        w = st.number_input("Velocidade Angular (rad/s)",
                            format="%g",
                            step=1.0)
        r = ""
    if st.button("Calcular"):
        result = calc(v, w, r)
    st.title(result)
예제 #15
0
def show_trending(data, data_city):
    st.header("Trending")
    st.sidebar.header("Trending")

    st.markdown("Daily new cases with rolling averages")

    opt = st.sidebar.selectbox("Select state or total", data.state.unique())
    data_city_hist = None

    # Handle city selector if a state was selected
    if opt != "TOTAL":
        data_city_filtered = data_city.query(f"state == '{opt}'")
        cities = data_city_filtered.city.unique()
        city = st.sidebar.selectbox("Select city or total",
                                    np.insert(cities, 0, 'TOTAL'))
        if city != "TOTAL":
            data_city_hist = lazy_read_data_city(opt, city)
    col = st.sidebar.radio("Data", ['newCases', 'newDeaths'])

    if data_city_hist is None:
        total = data.query(f"state == '{opt}'")
        fore_total = _model_and_fit(total.loc[:, col])
    else:
        total = data_city_hist
        fore_total = _model_and_fit(data_city_hist.loc[:, col])
    total = total.append(fore_total, sort=False)

    total.loc[:, 'Avg60'] = total[col].rolling(window=60).mean()
    total.loc[:, 'Avg30'] = total[col].rolling(window=30).mean()
    total.loc[:, 'AvgExp30'] = total[col].rolling(
        window=30, win_type='exponential').mean(tau=1)
    st.line_chart(total.loc[:,
                            [col, 'Avg60', 'Avg30', 'AvgExp30', 'predicted']])

    st.markdown(
        "Data source: [Number of confirmed cases of COVID-19 in Brazil](https://github.com/wcota/covid19br)"
    )

    st.header("Reproduction number (R0)")
    R0 = _calculate_r0(total)
    R7 = _calculate_r0(total, 8)
    arrow = ":small_red_triangle:" if R0 > R7 else ":small_red_triangle_down:"
    st.markdown(f"### R0 is {R0:.2f} {arrow} (1 week ago was {R7:.2f})")

    #st.subheader("The trends")
    #st.markdown("* Long term trends are represented by 30 and 60-day averages, the later being the strongest\n"
    #            "* Short term trend is strongly related to the exponential 30-day average\n"
    #            "* In few words, for the trend to be really going down, AvgExp30 should cross Avg60 down\n"
    #            "* Predicted line is made by a basic variational inference using Adam optimization. "
    #            "This could give a sense of where it is heading, not exact number")

    st.subheader("The R0")
    st.markdown(
        "* R0 indicate the average number of people a single infected person infects\n"
        "* There are different ways to model R0. Currently using AIDS model from from "
        "[DIETZ, K. The estimation of the basic reproduction for infectious diseases]"
        "(https://doi.org/10.1177%2F096228029300200103)")
    st.latex(r'''R_0 = 1 + \frac{D \ln(2)} {t_d}''')
    st.markdown("* D = duration of the infectious period\n"
                "* td = number of days to double cases")
예제 #16
0
def trabalho(t):
    result = 'W = 0 J'
    st.latex(r"W = F d cos(\alpha)")
    u = st.radio("", ["Ângulo em graus", "Ângulo em radianos"])
    if u == "Ângulo em graus":
        u = "º"
    else:
        u = "rad"
    if t == "Trabalho (J)":
        result = 'W = 0 J'
        w = ""
        f = st.number_input("Força (N)", format="%g", step=1.0)
        d = st.number_input("Deslocamento (m)", format="%g", step=1.0)
        a = st.number_input(f"Ângulo α ({u})", format="%g", step=1.0)
    elif t == "Força (N)":
        result = "F = 0 N"
        w = st.number_input("Trabalho (J)", format="%g", step=1.0)
        f = ""
        d = st.number_input("Deslocamento (m)", format="%g", step=1.0)
        a = st.number_input(f"Ângulo α ({u})", format="%g", step=1.0)
    elif t == "Deslocamento (m)":
        result = "d = 0 m"
        w = st.number_input("Trabalho (J)", format="%g", step=1.0)
        f = st.number_input("Força (N)", format="%g", step=1.0)
        d = ""
        a = st.number_input(f"Ângulo α ({u})", format="%g", step=1.0)
    elif t == "Ângulo α":
        result = f'α = 0 {u}'
        w = st.number_input("Trabalho (J)", format="%g", step=1.0)
        f = st.number_input("Força (N)", format="%g", step=1.0)
        d = st.number_input("Deslocamento (m)", format="%g", step=1.0)
        a = ""
    if st.button("Calcular"):
        result = calc(w, f, d, a, u)
    st.title(result)
예제 #17
0
def trabp(t):
    result = 'Wp = 0 J'
    st.latex(r"W_p = - \Delta E_p")
    if t == "Trabalho do peso (J)":
        result = 'W = 0 J'
        e = ""
        f = st.number_input("Energia potencial final (J)",
                            format="%g",
                            step=1.0)
        i = st.number_input("Energia potencial inicial (J)",
                            format="%g",
                            step=1.0)
    elif t == "Energia potencial final (J)":
        result = "Epf = 0 J"
        f = ""
        e = st.number_input("Trabalho do peso (J)", format="%g", step=1.0)
        i = st.number_input("Energia potencial inicial (J)",
                            format="%g",
                            step=1.0)
    elif t == "Energia potencial inicial (J)":
        result = "Epi = 0 J"
        i = ""
        e = st.number_input("Trabalho do peso (J)", format="%g", step=1.0)
        f = st.number_input("Energia potencial final (J)",
                            format="%g",
                            step=1.0)
    if st.button("Calcular"):
        result = calc(e, f, i)
    st.title(result)
예제 #18
0
def tec(t):
    result = 'Em = 0 J'
    st.latex(r"W = \Delta E_c")
    if t == "Trabalho (J)":
        result = 'W = 0 J'
        e = ""
        f = st.number_input("Energia cinética final (J)",
                            format="%g",
                            step=1.0)
        i = st.number_input("Energia cinética inicial (J)",
                            format="%g",
                            step=1.0)
    elif t == "Energia cinética inicial (J)":
        result = "Ecf = 0 J"
        f = ""
        e = st.number_input("Trabalho (J)", format="%g", step=1.0)
        i = st.number_input("Energia cinética inicial (J)",
                            format="%g",
                            step=1.0)
    elif t == "Energia cinética inicial (J)":
        result = "Eci = 0 J"
        i = ""
        e = st.number_input("Trabalho (J)", format="%g", step=1.0)
        f = st.number_input("Energia cinética final (J)",
                            format="%g",
                            step=1.0)
    if st.button("Calcular"):
        result = calc(e, f, i)
    st.title(result)
예제 #19
0
def resist(b):
    result = 'R = 0 Ω'
    st.latex(r"R = \frac{U}{I}")
    if b == "Resistência (Ω)":
        result = 'R = 0 Ω'
        r = ""
        u = st.number_input("Diferença de Potencial (V)",
                            format="%g",
                            step=1.0)
        i = st.number_input("Corrente Elétrica (A)", format="%g", step=1.0)
    elif b == "Diferença de Potencial (V)":
        result = "U = 0 V"
        r = st.number_input("Resistência (Ω)", format="%g", step=1.0)
        u = ""
        i = st.number_input("Corrente Elétrica (A)", format="%g", step=1.0)
    elif b == "Corrente Elétrica (A)":
        result = "I = 0 A"
        r = st.number_input("Resistência (Ω)", format="%g", step=1.0)
        u = st.number_input("Diferença de Potencial (V)",
                            format="%g",
                            step=1.0)
        i = ""
    if st.button("Calcular"):
        result = calc(r, u, i)
    st.title(result)
예제 #20
0
def main():
    st.title("Image to LaTeX")

    with st.form(key="imputs"):
        st.markdown("## Upload an Image")
        image = st.file_uploader("", type=["jpg", "png"])
        st.form_submit_button(label="Upload")

    with st.form(key="outputs"):
        st.markdown("## Convert to LaTeX")
        st.text("Uploaded image:")
        if image is not None:
            st.image(image)
        inference_button = st.form_submit_button(label="Infer")

    if inference_button and image is not None:
        with st.spinner("Wait for it..."):
            b64_image = base64.b64encode(image.read())
            response = requests.post(
                API_PREDICT_URL,
                json={"image": f"data:image/png;base64,{b64_image.decode()}"})
        if response.status_code == 200:
            st.markdown("**Inferred LaTex:**")
            st.code(response.json()["pred"], language="latex")
            st.markdown("**Render Inferred LaTeX:**")
            st.latex(response.json()["pred"])
        else:
            st.error("An error occurred in the model server.")
def fourier_frame():
    with st.expander("Create a Fourier Series"):
        # st.markdown('# Create a Fourier Series:')
        st.latex(r'\hat{f}(x) = \frac{a_0}{2} + \sum_{n=1}^{\infty}a_n\cos\bigg(\frac{2\pi n}{P}x\bigg) + '
                 r'\sum_{n=1}^{\infty}b_n\sin\bigg(\frac{2\pi n}{P}x\bigg)')
        selection_list = ['Sine', 'Cosine', 'Square', 'Triangle', 'Sawtooth', 'Gaussian']

        st.markdown('## Wave Options')
        type = st.selectbox('Wave Type', selection_list, 0)
        amp = st.slider('Amplitude', 0., 100., 1., 0.1, "%.1f")
        per = st.slider('Period (or Gaussian FWHM)', 0.01, 100., 2*np.pi, 0.01, "%.2f")
        phase = st.slider('Phase (or Gaussian Mean)', -np.pi, np.pi, 0., 0.01, "%.2f")
        velocity = st.number_input('Velocity (v)', int(0), int(100), int(0), int(1), "%d")
        rectify = st.checkbox('Rectify', False)

        st.markdown('## Fourier Series Options')
        ts = st.number_input('Draw Timestamp', 0., 100., 0., 0.1, "%.1f")
        iters = st.number_input('Iterations', int(1), int(100), int(10), int(1), "%d")
        cols = st.columns(2)
        min = cols[0].number_input(label='Interval Min', value=-np.pi)
        max = cols[1].number_input(label='Interval Max', value=np.pi)
        interval = (min, max)
        res = st.number_input(label='Resolution', value=1000)

        pchart = build_fourier(type, rectify, amp, per, phase, velocity, ts, iters, interval, res)
        st.plotly_chart(pchart, use_container_width=True)
예제 #22
0
def lie_brackets():
    st.latex(r'\text{Calculate Lie brackets $[A, B]$:}')
    c1, c2 = st.columns(2)
    with c1:
        A = st.text_input('A:')
    with c2:
        B = st.text_input('B:')
    if A and B:
        st.latex(jwitt.lie(A, B))
예제 #23
0
def main():
    st.title('Modelo SIQR')

    st.header('Ecuaciones del modelo')
    st.latex(r'''
    \left\{
    \begin{array}{l}
    S'= -aS\frac{I+(1-\sigma)Q}{N-\sigma Q}\\
    I'= aS\frac{I+(1-\sigma)Q}{N-\sigma Q}-(\theta+\alpha)I\\
    Q'=\theta I-\gamma Q\\
    R'=\alpha I+\gamma Q
    \end{array}
    \right.
    ''')

    st.sidebar.header('Parámetros del modelo')
    a = st.sidebar.number_input('a', min_value=0.0, max_value=10.0, value=2.0, step=0.1)
    sigma = st.sidebar.number_input('sigma', min_value=0.0, max_value=10.0, value=0.1, step=0.1)
    theta = st.sidebar.number_input('theta', min_value=0.0, max_value=10.0, value=1.0, step=0.1)
    alpha = st.sidebar.number_input('alpha', min_value=0.0, max_value=10.0, value=1.0, step=0.1)
    gamma = st.sidebar.number_input('gamma', min_value=0.0, max_value=10.0, value=1.0, step=0.1)

    st.sidebar.header('Condiciones iniciales')
    S0 = st.sidebar.number_input('S0', min_value=0, max_value=10000000, value=80, step=10)
    I0 = st.sidebar.number_input('I0', min_value=0, max_value=10000000, value=10, step=10)
    Q0 = st.sidebar.number_input('Q0', min_value=0, max_value=10000000, value=10, step=10)
    R0 = st.sidebar.number_input('R0', min_value=0, max_value=10000000, value=0, step=10)

    st.sidebar.header('Otras opciones')
    t_max = st.sidebar.number_input('t_max', min_value=10, max_value=1000, value=20, step=5)

    st.header('Solución del modelo')
    sol = solve_ivp(modelo_siqr, [0, t_max], [S0, I0, Q0, R0], args=(a, sigma, theta, alpha, gamma), dense_output=True)
    st.write(sol.message)

    t = np.arange(0, t_max, 0.01)
    Z = sol.sol(t)

    fig = go.Figure()
    names = ['S','I','Q','R']
    for i, z in enumerate(Z):
        fig.add_trace(go.Scatter(
            x=t,
            y=z,
            name=names[i],
            marker_color=px.colors.qualitative.D3[i]
        ))

    fig.update_layout(
        title='Soluciones del sistema SIQR',
        xaxis_title='t',
        template='ggplot2',
        height=500
    )

    st.plotly_chart(fig, use_container_width=True) 
def harmonic_frame():
    with st.expander("Look at Spherical Harmonics"):
        st.latex('Y_\ell^m(\\theta, \\phi) = \sqrt{\\frac{(2\ell + 1)}{4\pi}\\frac{(\ell - m)!}{(\ell + m)!}}'
                 'e^{im\phi}P_\ell^m(\cos\\theta)')
        st.latex(r'\ell \in \mathbb{N}_0 \ \ \ \ \ m \in \{-\ell,-\ell+1,...,\ell-1, \ell\}')
        st.markdown('## Harmonic Options')
        lH = st.number_input("l  ", int(0), int(100), int(0), int(1), "%d")
        mH = st.number_input("m  ", int(-lH), int(lH), int(0), int(1), "%d")
        fig = build_harmonic(lH, mH)
        st.plotly_chart(fig, use_container_width=True)
def hermite_frame():
    with st.expander("Look at Hermite Polynomials"):
        st.latex(r'H_n(x) = (-1)^n e^{x^2} \frac{d^n}{dx^n}e^{-x^2}')
        st.latex(r'n \in \mathbb{N}_0')
        st.markdown('## Hermite Options')
        collect_nums = lambda x: [int(i) for i in re.split("[^0-9]", x) if i != ""]
        filter_nums = lambda _list: [item for item in _list if (0 <= item <= 100)]
        nums = st.text_input("n [type any number of values to plot]", "0, 1, 2, 3, 4")
        nH = filter_nums(collect_nums(nums))
        fig = build_hermite(nH)
        st.plotly_chart(fig, use_container_width=True)
예제 #26
0
파일: latex.py 프로젝트: modiem/streamlit
def run():

    st.write(
        'Latex allows to display styled and structured text in your app, and is very useful in particular in order to display mathematical formulas'
    )

    with st.echo():
        st.latex(r'''
            a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
            \sum_{k=0}^{n-1} ar^k =
            a \left(\frac{1-r^{n}}{1-r}\right)
            ''')
예제 #27
0
파일: app.py 프로젝트: briancohan/t2fit
def find_best(df: pd.DataFrame):

    times = df.loc[df.used, 'Time']
    target = df.loc[df.used, 'HRR']

    iterations = 50
    guesses = pd.DataFrame([{
        'tv':
        tv,
        'tg':
        tg,
        'score':
        r2_score(target, t2_hrr(times.values, tv=tv, tg=tg))
    } for tv in np.linspace(0, times.max(), iterations)
                            for tg in np.linspace(1, times.max(), iterations)])

    tv = st.sidebar.slider(
        'Virtual Time',
        min_value=0,
        max_value=int(times.max()),
        value=int(guesses.iloc[guesses.idxmax().score].tv),
    )
    tg = st.sidebar.slider(
        'Growth Time',
        min_value=0,
        max_value=int(times.max()),
        value=int(guesses.iloc[guesses.idxmax().score].tg),
    )

    fit = pd.DataFrame({
        'Time': times,
        'curve': 'fit',
        'HRR': t2_hrr(times.values, tv=tv, tg=tg),
    })
    score = r2_score(target, fit.HRR)

    st.latex(f'\\dot{{Q}}'
             f'=\\dot{{Q}}_{{ref}}\\left(\\frac{{t-t_v}}{{t_g}}\\right)^2'
             f'={QREF} kW\\left(\\frac{{t-{tv} s}}{{{tg} s}}\\right)^2')
    st.latex(f'R^2={{{score:.3f}}}')

    cht = alt.Chart(pd.concat([df, fit])).mark_line().encode(x='Time',
                                                             y='HRR',
                                                             color='curve')
    st.altair_chart(cht, use_container_width=True)

    st.sidebar.markdown(f'''
    # Results
    $\\dot{{Q}}_{{max}}$ | $t_v$ | $t_g$
    :---:|:---:|:---:
    {df.HRR.max():.0f} kW | {tv} s | {tg} s
    ''')
예제 #28
0
    def test_sympy_expression(self):
        try:
            import sympy

            a, b = sympy.symbols("a b")
            out = a + b
        except:
            out = "a + b"

        st.latex(out)

        c = self.get_delta_from_queue().new_element.markdown
        self.assertEqual(c.body, "$$\na + b\n$$")
예제 #29
0
    def render_probability_table(self):

        #st.subheader("Probability Table")

        vect = self.model.named_steps['vect']
        tokenizer = vect.build_tokenizer()
        prediction_array = tokenizer(self.input_string)
        prediction_array.append(self.input_string)

        probabilities = pd.DataFrame(
            self.model.predict_proba(prediction_array).transpose())
        probabilities.columns = prediction_array
        probabilities.columns = [
            *probabilities.columns[:-1], 'Combined Probability'
        ]
        probabilities.insert(0, "character", self.model.classes_)
        probabilities.set_index('character', inplace=True)
        probabilities.sort_values(by=['Combined Probability'],
                                  ascending=False,
                                  inplace=True)

        used_column_names = []
        column_names = probabilities.columns.to_numpy()
        for i in range(0, len(column_names)):
            while column_names[i] in used_column_names:
                column_names[i] = column_names[i] + " "

            used_column_names.append(column_names[i])

        probabilities.columns = column_names

        self.prediction_probs = probabilities

        st.dataframe(
            self.prediction_probs.style.background_gradient(cmap=plt.cm.Reds,
                                                            high=0.35))

        st.text(
            "The table above shows the probabilities the model predicts given a character the input.\n"
            "Each cell holds the probability of predicting its row's character given its column's\n"
            "word. In other words:")
        st.latex("cell(row, column)=P(character|word)")
        st.text(
            "The final column represents the probability our model predicts a character given the\n"
            "entire input string together.  The character with the largest value in this column\n"
            "is our model's prediction.  One character words like 'I' and 'a' are removed because\n"
            "they don't provide any useful information to the model.  No other words are removed."
        )
        st.text(
            "By clicking on the names of the columns, you can sort the table and see which\n"
            "character is most likely to say a word.")
    def calc_solidity_factor(self):
        """
        For AS1170, signs may have a perforated hoarding, which can reduce the wind pressure
        """
        args = {'delta': self.solidity, 'C_pn': self.C_pn}

        def calc_K_p_func(delta, C_pn):
            K_p = 1 - (1 - delta)**2
            C_fig = C_pn * K_p
            return C_fig, K_p

        K_p_latex, (self.C_fig, self.K_p) = helper_funcs.func_by_run_type(
            self.wind.Wind_mult.render_hc, args, calc_K_p_func)
        if self.wind.Wind_mult.render_hc: st.latex(K_p_latex)