Best Python code snippet using fMBT_python
test_odassl.py
Source:test_odassl.py  
1from scipy import *2import odassl as od3g=13.7503716373294544 # gravitation constant such that the period is 24def tolerance_set(irun,tol):5    rtol=atol=tol*ones((5,))6    if irun == 1 or irun == 3:7       rtol[4]=atol[4]=1.e78    elif irun == 0:                                                                9       rtol[2:]=atol[2:]=1.e7                                                    10    info=111    return rtol,atol,info            12def res1(t,p,pp):13    ires=0                                                                                                                      14    delta=empty((5,))                                                      15    # kinematics                                                                               16    delta[0:2] = [pp[0] - p[2], pp[1] - p[3]]                                                                         17    # dynamics                                                  18    delta[2:4] =  [pp[2] + p[4]*p[0], pp[3]+p[4]*p[1]+g]                                             19    # lambda constraint                                                              20    delta[4] = p[2]**2 + p[3]**2 - (p[0]**2 + p[1]**2)*p[4] - p[1]*g                                          21    return delta, ires22def res2(t,p,pp):23    ires=0                                                                      24    delta=empty((5,))                                                      25    # kinematics                                                                               26    delta[0:2] = [pp[0] - p[2], pp[1] - p[3]]                                                                         27    # dynamics                                                  28    delta[2:4] =  [pp[2] + p[4]*p[0], pp[3]+p[4]*p[1]+g]                                             29    # velocity constraint                                                              30    delta[4] = p[0]*p[2] + p[1]*p[3]                                          31    return delta, ires32def res3(t,p,pp):33    ires=0                                                                      34    delta=empty((5,))   35    #print t,p,pp                                                   36    # kinematics                                                                               37    delta[0:2] = [pp[0] - p[2], pp[1] - p[3]]                                                                         38    # dynamics                                                  39    delta[2:4] =  [pp[2] + p[4]*p[0], pp[3]+p[4]*p[1]+g]                                             40    # position constraint                                                              41    delta[4] = p[0]**2 + p[1]**2 - 1.0                                           42    return delta, ires43def resStab2(t,p,pp):44    ires=0                                                                      45    delta=empty((neq,))   46    #print t,p,pp                                                   47    # kinematics                                                                               48    delta[0:2] = [pp[0] - p[2], pp[1] - p[3]]                                                                         49    # dynamics                                                  50    delta[2:4] =  [pp[2] + p[4]*p[0], pp[3]+p[4]*p[1]+g]51    # velocity constraint  52    delta[4] = p[0]*p[2] + p[1]*p[3]                                            53    # position constraint                                                              54    delta[5] = p[0]**2 + p[1]**2 - 1.0                                           55    return delta, ires    56def resStab1(t,p,pp):57    ires=0                                                                      58    delta=empty((neq,))   59    #print t,p,pp                                                   60    # kinematics                                                                               61    delta[0:2] = [pp[0] - p[2], pp[1] - p[3]]                                                                         62    # dynamics                                                  63    delta[2:4] =  [pp[2] + p[4]*p[0], pp[3]+p[4]*p[1]+g]64    # lambda constraint65    delta[4] = p[2]**2 + p[3]**2 - (p[0]**2 + p[1]**2)*p[4] - p[1]*g66    # velocity constraint  67    delta[6] = p[0]*p[2] + p[1]*p[3]                                            68    # position constraint                                                              69    delta[5] = p[0]**2 + p[1]**2 - 1.0                                           70    return delta, ires    71p=empty(5)72pp=empty(5)73rwork=empty((1000,))74iwork=empty((200,),dtype=int32)  75                                                  76ny = 5                                                                    77tol= 1.e-5       78res=[res3,res2,res1, resStab2, resStab1]                                                 79for irun, task in enumerate(['INDEX-3', 'INDEX-2',80             'INDEX-1', 81             'STAB. INDEX-2','STAB. INDEX-1']):82     83     info=zeros((15,),dtype=int32)                                                                                         84     # initial conditions                                                                                                                                               85     p[0] = 1.0                                                             86     p[1] = -sqrt(1.0 - p[0]**2)                                           87     p[2:] = 0.0                                                                                                                         88     pp[0:2] = p[2:4]                                                           89     pp[2:5] = [-p[4]*p[0], -g-p[4]*p[1],0.]                                                                                                                        90     # other initialisations                                                                                                                                                                        91     t,th = 0., 2.0                                                            92                                                             93     rtol,atol,info[1] = tolerance_set(irun,tol)                                                                             94     ny=len(p)95     if irun <= 2:                                                                    96        neq=ny                                 97     elif irun==3:  # stab index 2                                                                   98        neq=ny+1                                        99     elif irun==4:  # stab index 1100        neq=ny+2                                                                 101#          INTEGRATION LOOP                                                     102     for i in range(50):103         tout=t+th                        104         t,y,yprime,tout,info,idid,rwork,iwork = od.odassl(res[irun],neq,ny,t,p,pp,tout,info,rtol,atol,105                                                         rwork,iwork,res[irun])                                                                                106         if idid<0:                              107            print task+':  ', idid                                                  108            break                                                         109         else:                                                                110            print '{0}  : t= {1: >8.2f}  p={2[0]: >-12.8f} {2[1]: > 12.8f} {2[2]: >-12.8f} {2[3]: >-12.8f} {2[4]: >-12.8f}'.format(task, t, p)                            ...minidisc_masses.py
Source:minidisc_masses.py  
1import matplotlib as mpl2mpl.use('Agg')3import matplotlib.pyplot as plt4import pandas as pd5import numpy as np6from scipy import interpolate7data_dir = "../analysis_out/"8norad_folder = "norad_prod"9rad_folder = "rad_prod"10sim_name_bases = ["small_ecc","small_circ"]11rad_format = "rad_{}_full"12rad_format_earlier = "rad_{}_earlier"13data_file_format = data_dir+"disc_components_{}_{}.txt"14t_orbit = 13.7e-3 # Myr15m_bh = 2.e316t_offset = 0.0002128*0.9778e9/1.e617norad_data_unprocessed = [pd.read_csv(data_file_format.format(norad_folder,sim_name_bases[irun]),sep=' ') for irun in [0,1]]18rad_data = [pd.read_csv(data_file_format.format(rad_folder,rad_format.format(sim_name_bases[irun])),sep=' ') for irun in [0,1]]19rad_data_earlier = [pd.read_csv(data_file_format.format(rad_folder,rad_format_earlier.format(sim_name_bases[irun])),sep=' ') for irun in [0,1]]20# interpolate norad_data to make timing consistent21norad_data = []22for df in norad_data_unprocessed:23    dt = df["t"].iloc[-1]-df["t"].iloc[-2]24    interp_t = np.arange(0,df["t"].iloc[-1],dt)25    new_df = pd.DataFrame()26    new_df["t"] = interp_t27    new_df["m1"] = interpolate.interp1d(df["t"],df["m1"])(interp_t)28    new_df["m2"] = interpolate.interp1d(df["t"],df["m2"])(interp_t)29    norad_data.append(new_df)30# yticks = [0,5e-4,1e-3,3e-3,5e-3,1e-2]31fig,sp = plt.subplots(1,2,figsize=(9,3),sharex=True,sharey=True,constrained_layout=True)32for irun in range(2):33    for idisc in [1,2]:34        for t,m,label in [(norad_data[irun]["t"], norad_data[irun][f"m{idisc}"], f"disc{idisc}"),35                          (rad_data[irun]["t"] + norad_data[irun]["t"].iloc[-1], rad_data[irun][f"m{idisc}"], None),36                          (rad_data_earlier[irun]["t"] + t_offset, rad_data_earlier[irun][f"m{idisc}"], None)37                          ]:38            sp[irun].plot(t / t_orbit, m / m_bh, label=label)39            # orbit_t = t/t_orbit40            # interp_t = np.arange(int(orbit_t[0]),orbit_t[-1],1)41        # sp[irun].plot(norad_data[irun]["t"]/t_orbit,norad_data[irun][f"m{idisc}"]/m_bh,label=f"disc{idisc}")42        # sp[irun].plot((rad_data[irun]["t"]+norad_data[irun]["t"].iloc[-1])/t_orbit,rad_data[irun][f"m{idisc}"]/m_bh)43        # sp[irun].plot((rad_data_earlier[irun]["t"]+t_offset)/t_orbit,rad_data_earlier[irun][f"m{idisc}"]/m_bh)44    # sp[irun].legend()45    sp[irun].minorticks_on()46    sp[irun].xaxis.set_minor_locator(plt.MultipleLocator(1))47    sp[irun].set_xlim([0,None])48    # sp[irun].set_ylim([0,1.e-2])49    sp[irun].set_ylim([0,0.003])50    # sp[irun].set_yscale('symlog',linthresh=1.e-3)51    # sp[irun].set_yticks(yticks)52    # sp[irun].set_yticklabels(yticks)53    sp[irun].set_xlabel(r"$t$ (orbits)")54sp[0].set_ylabel(r"$M_d/(M_1+M_2)$")55sp[0].set_title("Elliptical")56sp[1].set_title("Circular")...torque_significance.py
Source:torque_significance.py  
1import numpy as np2import h5py3from num2tex import num2tex4f = h5py.File("../analysis_out/tidy_torque.hdf5",'r')5def get_exponent(x):6    return np.floor(np.log10(np.abs(x))).astype(np.int)7def format_with_uncertainty(x,e,precision=1,significance=3):8    # fmt = fr"({{0:.{precision}f}} \pm {{1:.{precision}f}}) \times 10^{{{{{{2}}}}}}"9    #10    # exponents = np.minimum(get_exponent(x),get_exponent(e))11    # bases = x/10.**exponents12    # error_bases = e/10.**exponents13    # strout = fmt.format(bases,error_bases,exponents)14    round_factor = -np.floor(np.log10(e)).astype(np.int) + precision-115    x_round = np.round(x,round_factor)16    e_round = np.round(e,round_factor)17    if round_factor<0:18        strout = fr"{{{x_round:.0f}}} \pm {{{e_round:.0f}}}"19    else:20        strout_0 = fr"{{0:.{round_factor:0d}f}} \pm {{1:.{round_factor:0d}f}}"21        strout = strout_0.format(x_round,e_round)22    # strout = fr"{{{x:.3f}}} \pm {{{e:.3f}}}"23    # if np.abs(bases)>np.abs(error_bases):24    if np.abs(x) > significance*np.abs(e) :25            strout = r"$\mathbf{"+strout+r"}$"26    else:27        strout = r"$"+strout+r"$"28    # TODO: implement for arrays?29    return strout30stage_name = [r"norad\_all", r"norad\_eqm", r"rad\_early", r"rad\_late"]31torque_name = {"grav":r"$\tau_g$",32                "acc":r"$\tau_a$"33    }34run_indices = [0,0,1,2]35run_offsets = [0,20,0,0]36nruns = len(run_indices)37assert nruns==len(run_offsets)38# UNITS = L0/T (set in tidy_up_torque)39for plot_key in ["acc","grav"]:40    mu = np.zeros((2,2,nruns))41    sd = np.zeros((2,2,nruns))42    for isim in range(2):43        for bh in [1,2] :44            for irun,run_index in enumerate(run_indices):45                time = np.array(f[f"time_{run_index}_{isim}"])46                h5_key = f"BH_{plot_key}_J_{bh}_{run_index}_{isim}"47                angmom = -np.array(f[h5_key])48                torque = np.gradient(angmom,time)49                run_offset = run_offsets[irun]50                if run_offset>0:51                    torque = torque[(time>run_offset)]52                mu[isim,bh-1,irun] = np.mean(torque)53                sd[isim,bh-1,irun] = np.std(torque)/np.sqrt(len(torque))54    for irun in range(nruns):55        line = []56        for isim in range(2) :57            for bh in range(2) :58                line+=[format_with_uncertainty(mu[isim,bh,irun]*1e6,sd[isim,bh,irun]*1e6,precision=2)]59                # line+=[fr"${num2tex(mu[isim,bh,irun],precision=2):.2g} \pm {num2tex(sd[isim,bh,irun],precision=2):.0g}$"]60        if irun==1:61            key_str = torque_name[plot_key]+" & "62        else:63            key_str = "~ & "64        print(key_str+stage_name[irun]+" & "+r" & ".join(line)+r"\\")...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!!
