Best Python code snippet using yandex-tank
pulseq_jemris_simulator.py
Source:pulseq_jemris_simulator.py  
1# Same role as pulseq_bloch_simulator.py except (1) It uses JEMRIS (2) It is run as a function, not a script2# INPUTS: sequence type, geometry parameters, contrast parameters,3#         phantom type (pre-set or custom), coil type (pre-set or custom) (Tx / Rx),4#         k-space trajectory (if noncartesian; flattened version (Nro_total, 3))5import time6import os7from virtualscanner.server.simulation.py2jemris.sim_jemris import sim_jemris8from virtualscanner.server.simulation.py2jemris.recon_jemris import read_jemris_output, recon_jemris9from virtualscanner.server.simulation.py2jemris.coil2xml import coil2xml10from virtualscanner.utils import constants11from virtualscanner.server.simulation.py2jemris.seq2xml import seq2xml12from pypulseq.Sequence.sequence import Sequence13import virtualscanner.server.simulation.bloch.phantom as pht14import numpy as np15import xml.etree.ElementTree as ET16from virtualscanner.server.simulation.bloch.pulseq_library import make_pulseq_se_oblique,\17    make_pulseq_gre_oblique, make_pulseq_irse_oblique18from scipy.io import savemat, loadmat19PY2JEMRIS_PATH = constants.SERVER_SIM_BLOCH_PY2JEMRIS_PATH20def simulate_pulseq_jemris(seq_path, phantom_info, coil_fov,21                           tx='uniform', rx='uniform', # TODO add input that includes sequence info for22                                                       # TODO      dimensioning the RO points into kspace23                           tx_maps=None, rx_maps=None, sim_name=None, env_option="local"):24    """Runs simulation using an already-made .seq file25    Inputs26    ------27    seq_path : str28        Path to seq file29    phantom_info : dict30        Information used to create phantom; input to create_and_save_phantom()31    coil_fov : float32        Field-of-view of coil in mm33    tx : str, optional34        Type of tx coil; default is 'uniform'; the only other option is 'custom'35    rx : str, optional36        Type of rx coil; default is 'uniform'; the only other option is 'custom'37    tx_maps : list, optional38        List of np.ndarray (dtype='complex') maps for all tx channels39        Required for 'custom' type tx40    rx_maps : list, optional41        List of np.ndarray (dtype='complex') maps for all rx channels42        Required for 'custom' type rx43    sim_name : str, optional44        Used as folder name inside sim folder45        Default is None, in which case sim_name will be set to the current timestamp46    Returns47    -------48    sim_output :49        Delivers output from sim_jemris50    """51    if sim_name is None:52        sim_name = time.strftime("%Y%m%d%H%M%S")53    if env_option == 'local':54        target_path = PY2JEMRIS_PATH / 'sim' / sim_name55    elif env_option == 'colab':56        target_path = 'sim/' + sim_name57    # Make target folder58    dir_str = f'{str(PY2JEMRIS_PATH)}\\sim\\{sim_name}'59    if not os.path.isdir(dir_str):60        os.system(f'mkdir {dir_str}')61    # Convert .seq to .xml62    seq = Sequence()63    seq.read(seq_path)64    seq_name = seq_path[seq_path.rfind('/')+1:seq_path.rfind('.seq')]65    seq2xml(seq, seq_name=seq_name, out_folder=str(target_path))66    # Make phantom and save as .h5 file67    pht_name = create_and_save_phantom(phantom_info, out_folder=target_path)68    # Make sure we have the tx/rx files69    tx_filename = tx + '.xml'70    rx_filename = rx + '.xml'71    # Save Tx as xml72    if tx == 'uniform':73        os.system(f'copy sim\\{tx}.xml {str(target_path)}')74    elif tx == 'custom' and tx_maps is not None:75        coil2xml(b1maps=tx_maps, fov=coil_fov, name='custom_tx', out_folder=target_path)76        tx_filename = 'custom_tx.xml'77    else:78        raise ValueError('Tx coil type not found')79    # save Rx as xml80    if rx == 'uniform':81        os.system(f'copy sim\\{rx}.xml sim\\{str(target_path)}')82    elif rx == 'custom' and rx_maps is not None:83        coil2xml(b1maps=rx_maps, fov=coil_fov, name='custom_rx', out_folder=target_path)84        rx_filename = 'custom_rx.xml'85    else:86        raise ValueError('Rx coil type not found')87    # Run simuluation in target folder88    list_sim_files = {'seq_xml': seq_name+'.xml', 'pht_h5': pht_name + '.h5', 'tx_xml': tx_filename,89                       'rx_xml': rx_filename}90    sim_output = sim_jemris(list_sim_files=list_sim_files, working_folder=target_path)91    return sim_output92# TODO93def create_and_save_phantom(phantom_info, out_folder):94    """Generates a phantom and saves it into desired folder as .h5 file for JEMRIS purposes95    Inputs96    ------97    phantom_info : dict98        Info of phantom to be constructed99        REQUIRED100        'fov' : float, field-of-view [meters]101        'N' : int, phantom matrix size (isotropic)102        'type' : str, 'spherical', 'cylindrical' or 'custom'103        'dim' : int, either 3 or 2; 3D or 2D phantom options104        'dir' : str, {'x', 'y', 'z'}; orientation of 2D phantom105        OPTIONAL (only required for 'custom' phantom type)106        'T1' : np.ndarray, T1 map matrix107        'T2' : np.ndarray, T2 map matrix108        'PD' : np.ndarray, PD map matrix109        'dr' : float, voxel size [meters] (isotropic)110        'dBmap' : optional even for 'custom' type. If not provided, dB is set to 0 everywhere.111    out_folder : str or pathlib Path object112        Path to directory where phantom will be saved113    Returns114    -------115    pht_type : str116        phantom_info['pht_type'] (returned for naming purposes)117    """118    out_folder = str(out_folder)119    FOV = phantom_info['fov']120    N = phantom_info['N']121    pht_type = phantom_info['type']122    pht_dim = phantom_info['dim']123    pht_dir = phantom_info['dir']124    sim_phantom = 0125    if pht_type == 'spherical':126        print('Making spherical phantom')127        T1s = [1000]128        T2s = [100]129        PDs = [1]130        R = 0.8*FOV/2131        Rs = [R]132        if pht_dim == 3:133            sim_phantom = pht.makeSphericalPhantom(n=N, fov=FOV, T1s=T1s, T2s=T2s, PDs=PDs, radii=Rs)134        elif pht_dim == 2:135            sim_phantom = pht.makePlanarPhantom(n=N, fov=FOV, T1s=T1s, T2s=T2s, PDs=PDs, radii=Rs,136                                                dir=pht_dir, loc=0)137    elif pht_type == 'cylindrical':138        print("Making cylindrical phantom")139        sim_phantom = pht.makeCylindricalPhantom(dim=pht_dim, n=N, dir=pht_dir, loc=0)140    elif pht_type == 'custom':141        # Use a custom file!142        T1 = phantom_info['T1']143        T2 = phantom_info['T2']144        PD = phantom_info['PD']145        dr = phantom_info['dr']146        if 'dBmap' in phantom_info.keys():147            dBmap = phantom_info['dBmap']148        else:149            dBmap = 0150        sim_phantom = pht.Phantom(T1map=T1, T2map=T2, PDmap=PD, vsize=dr, dBmap=dBmap, loc=(0,0,0))151    else:152        raise ValueError("Phantom type non-existent!")153    # Save as h5154    sim_phantom.output_h5(out_folder, pht_type)155    return pht_type156if __name__ == '__main__':157    # Define the same phantom158    phantom_info = {'fov': 0.256, 'N': 32, 'type': 'cylindrical', 'dim':2, 'dir':'z'}159    sim_names = ['test0413_GRE', 'test0413_SE', 'test0413_IRSE']160    sps = ['gre_fov256mm_Nf15_Np15_TE50ms_TR200ms_FA90deg.seq',161           'se_fov256mm_Nf15_Np15_TE50ms_TR200ms_FA90deg.seq',162           'irse_fov256mm_Nf15_Np15_TI20ms_TE50ms_TR200ms_FA90deg.seq']163    # make_pulseq_irse_oblique(fov=0.256,n=15, thk=0.005, tr=0.2, te=0.05, ti=0.02, fa=90,164    #                          enc='xyz', slice_locs=[0], write=True)165    # make_pulseq_gre_oblique(fov=0.256,n=15, thk=0.005, tr=0.2, te=0.05, fa=90,166    #                          enc='xyz', slice_locs=[0], write=True)167    # make_pulseq_se_oblique(fov=0.256,n=15, thk=0.005, tr=0.2, te=0.05, fa=90,168    #                          enc='xyz', slice_locs=[0], write=True)169    simulate_pulseq_jemris(seq_path=sps[0], phantom_info=phantom_info, sim_name=sim_names[0],170                               coil_fov=0.256)171    kk, im, images = recon_jemris(file='sim/' + sim_names[0] + '/signals.h5', dims=[15,15])...sim_seq_validation.py
Source:sim_seq_validation.py  
1import os2from pulseq_jemris_simulator import simulate_pulseq_jemris, recon_jemris3from scipy.io import savemat, loadmat456# IRSE7n = 328phantom_info = {'fov': 0.25, 'N': n, 'type': 'cylindrical', 'dim': 2, 'dir': 'z', 'loc': 0}9sps = 'sim/seq_validation/irse_32/irse32.seq'10sim_name = 'seq_validation\\irse_32'1112#Simulate13simulate_pulseq_jemris(seq_path=sps, phantom_info=phantom_info, sim_name=sim_name, coil_fov=0.25)14kk, im, images = recon_jemris(file='sim/' + sim_name + '/signals.h5', dims=[n, n])15savemat('sim/' + sim_name + '/utest_pulseq_sim_output.mat', {'images': images, 'kspace': kk, 'imspace': im})161718# #19# # TSE20# n = 3221# phantom_info = {'fov': 0.25, 'N': n, 'type': 'cylindrical', 'dim': 2, 'dir': 'z', 'loc': -0.08}22# sps = 'sim/seq_validation/tse_32/tse32.seq'23# sim_name = 'seq_validation\\tse_32'24# # Make sequence25# simulate_pulseq_jemris(seq_path=sps, phantom_info=phantom_info, sim_name=sim_name, coil_fov=0.25)26# kk, im, images = recon_jemris(file='sim/' + sim_name + '/signals.h5', dims=[n, n])27# savemat('sim/' + sim_name + '/TSE-T2PLANE-utest_pulseq_sim_output.mat', {'images': images, 'kspace': kk, 'imspace': im})28#2930# ## DWI31# n = 3232# phantom_info = {'fov':0.25, 'N':n, 'type': 'cylindrical', 'dim': 2, 'dir': 'z', 'loc': -0.08}33# sps = 'sim/seq_validation/dwi_32/dwi32.seq'34# sim_name = 'seq_validation\\tse_32'35#36# simulate_pulseq_jemris(seq_path=sps, phantom_info=phantom_info, sim_name=sim_name, coil_fov=0.25)37# kk, im, images = recon_jemris(file='sim/'+sim_name+'/signals.h5',dims=[n,n])
...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!!
