Пример #1
0
# build our format array so that we can pass it to the plotting tools functions
plot_formats = c.get_plot_format()

# array to store the experiment objects
experiments = []

# go through each input file and create an experiment object
for i in range(1, len(sys.argv)):
    if not sys.argv[i].endswith('.ini'):
        source_file = sys.argv[i]
        source_file.strip()
        if not source_file.endswith('/'):
            source_file += '/'
        experiments.append(
            experiment.Experiment(source_file, c.epoch_modifier,
                                  c.use_properties))

# epoch modifier allows us to step through large datasets quickly, calculating only the values of generations
# divisible by the modifier
# epoch_modifier = 5  epoch modifier should be specified from config file

plot.load(c)

#create list of all the graph labels
labels = [
    'Max Fitness', 'Minimum Fitness', 'Average Fitness', 'Champion Complexity',
    'Max Complexity', 'Minimum Complexity', 'Average Complexity'
]
# create a list of all the boolean values
show = c.get_standard_plot_options()
def rabiflops_standalone(
    init_gpa=False,
    larmorFreq=3.07436,
    rfExAmp=0.4,
    rfReAmp=None,
    rfExPhase=0,
    rfExTimeIni=6,
    rfExTimeEnd=60,
    nExTime=10,
    nReadout=800,
    tAdq=4 * 1e3,
    tEcho=20 * 1e3,
    tRepetition=3000 * 1e3,
    plotSeq=0,
    pulse='Rec',  # 'Rec' to Rectangular pulse, 'Sinc' for sinc pulse
    shimming=[-80, -100, 10]):

    #  INITALISATION OF VARIABLES  ################################################################################
    #CONTANTS
    tStart = 20
    txGatePre = 15
    txGatePost = 1
    oversamplingFactor = 6
    shimming = np.array(shimming) * 1e-4

    #ARRAY INITIALIZATIONS
    txTime = []
    txAmp = []
    txGateTime = []
    txGateAmp = []
    rxTime = []
    rxAmp = []
    dataAll = []

    #RF PULSES
    if rfReAmp is None:
        rfReAmp = rfExAmp
    rfExPhase = rfExPhase * np.pi / 180
    rfExAmp = rfExAmp * np.exp(1j * rfExPhase)
    rfRePhase = 0
    rfReAmp = rfReAmp * np.exp(1j * rfRePhase)
    #Excitation times
    rfExTime = np.linspace(rfExTimeIni, rfExTimeEnd, nExTime, endpoint=True)

    #  DEFINITION OF PULSES   ####################################################################################
    def rfSincPulse(tStart, rfTime, nLobes, rfAmplitude, rfPhase):
        txTime = np.linspace(tStart, tStart + rfTime, num=100,
                             endpoint=True) + txGatePre
        tMax = (nLobes + 1) / 2
        tx = np.linspace(-tMax, tMax, num=100, endpoint=True)
        txAmp = rfAmplitude * np.abs(np.sinc(tx))
        txGateTime = np.array([tStart, tStart + txGatePre + rfTime])
        txGateAmp = np.array([1, 0])
        return txTime, txAmp, txGateTime, txGateAmp

    def rfPulse(tRef, rfAmp, rfDuration, txTimePrevious, txAmpPrevious,
                txGateTimePrevious, txGateAmpPrevious):
        txTime = np.array([tRef - rfDuration / 2, tRef + rfDuration / 2])
        txAmp = np.array([rfAmp, 0.])
        txGateTime = np.array([txTime[0] - txGatePre, txTime[1] + txGatePost])
        txGateAmp = np.array([1, 0])
        txTime = np.concatenate((txTimePrevious, txTime), axis=0)
        txAmp = np.concatenate((txAmpPrevious, txAmp), axis=0)
        txGateTime = np.concatenate((txGateTimePrevious, txGateTime), axis=0)
        txGateAmp = np.concatenate((txGateAmpPrevious, txGateAmp), axis=0)
        return txTime, txAmp, txGateTime, txGateAmp

    def readoutGate(tRef, tRd, rxTimePrevious, rxAmpPrevious):
        rxTime = np.array([tRef - tRd / 2, tRef + tRd / 2])
        rxAmp = np.array([1, 0])
        rxTime = np.concatenate((rxTimePrevious, rxTime), axis=0)
        rxAmp = np.concatenate((rxAmpPrevious, rxAmp), axis=0)
        return rxTime, rxAmp

#  SPECIFIC FUNCTIONS   ####################################################################################

    def plotData(data, rfExTime, tAdqReal):
        plt.figure(1)
        colors = cm.rainbow(np.linspace(0, 0.8, len(rfExTime)))
        for indexExTime in range(nExTime):
            tPlot = np.linspace(
                -tAdqReal / 2, tAdqReal / 2, nReadout, endpoint='True') * 1e-3
            leg = 'Time = ' + str(np.round(rfExTime[indexExTime])) + 'us'
            plt.plot(tPlot[5:],
                     np.abs(data[indexExTime, 5:]),
                     label=leg,
                     color=colors[indexExTime])
#            plt.plot(tPlot[5:], np.real(data[indexExTime, 5:]))
#            plt.plot(tPlot[5:], np.imag(data[indexExTime, 5:]))
        plt.xlabel('t(ms)')
        plt.ylabel('A(mV)')
        plt.legend()

    def plotRabiFlop(data, rfExTime, tAdqReal):
        for indexExTime in range(nExTime):
            #            np.max(np.abs(data[indexExTime, 5:]))
            if indexExTime == 0:
                maxEchoes = np.max(np.abs(data[indexExTime, 5:]))
            else:
                maxEchoes = np.append(maxEchoes,
                                      np.max(np.abs(data[indexExTime, 5:])))
        plt.figure(2)
        plt.plot(rfExTime, maxEchoes)
        plt.xlabel('t(us)')
        plt.ylabel('A(mV)')
        titleRF = 'RF Amp = ' + str(np.real(rfExAmp))
        plt.title(titleRF)

#  SEQUENCE  ############################################################################################

    for indexExTime in range(nExTime):

        rfReTime = 2 * rfExTime[indexExTime]

        txTime = []
        txAmp = []
        txGateTime = []
        txGateAmp = []
        rxTime = []
        rxAmp = []

        # INIT EXPERIMENT
        BW = nReadout / tAdq
        BWov = BW * oversamplingFactor
        samplingPeriod = 1 / BWov
        expt = ex.Experiment(lo_freq=larmorFreq,
                             rx_t=samplingPeriod,
                             init_gpa=init_gpa,
                             gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
        samplingPeriod = expt.get_rx_ts()[0]
        BWReal = 1 / samplingPeriod / oversamplingFactor
        tAdqReal = nReadout / BWReal
        tIni = 20  #us initial time
        # Shimming
        expt.add_flodict({
            'grad_vx': (np.array([tIni]), np.array([shimming[0]])),
            'grad_vy': (np.array([tIni]), np.array([shimming[1]])),
            'grad_vz': (np.array([tIni]), np.array([shimming[2]])),
        })
        # TR
        tRef = tStart + rfExTime[indexExTime] / 2 + tIni + 100
        #        if pulse=='Rec':
        txTime, txAmp, txGateTime, txGateAmp = rfPulse(tRef, rfExAmp,
                                                       rfExTime[indexExTime],
                                                       txTime, txAmp,
                                                       txGateTime, txGateAmp)
        #        elif pulse=='Sinc':
        #            txTime, txAmp,txGateTime,txGateAmp = rfSincPulse(tRef,rfExAmp, rfExTime[indexExTime], txTime, txAmp, txGateTime, txGateAmp)
        tRef = tRef + tEcho / 2
        #        if pulse=='Rec':
        txTime, txAmp, txGateTime, txGateAmp = rfPulse(tRef, rfReAmp, rfReTime,
                                                       txTime, txAmp,
                                                       txGateTime, txGateAmp)
        #        if pulse=='Sinc':
        #            txTime, txAmp, txGateTime, txGateAmp = rfSincPulse(tRef,rfReAmp, rfReTime, txTime, txAmp, txGateTime, txGateAmp)
        tRef = tRef + tEcho / 2
        rxTime, rxAmp = readoutGate(tRef, tAdqReal, rxTime, rxAmp)

        expt.add_flodict({
            'tx0': (txTime, txAmp),
            'tx_gate': (txGateTime, txGateAmp),
            'rx0_en': (rxTime, rxAmp),
            'rx_gate': (rxTime, rxAmp),
        })
        tEnd = tRepetition
        expt.add_flodict({
            'grad_vx': (np.array([tEnd]), np.array([0])),
            'grad_vy': (np.array([tEnd]), np.array([0])),
            'grad_vz': (np.array([tEnd]), np.array([0])),
        })

        if plotSeq == 0:
            print(indexExTime, '.- Running...')
            rxd, msgs = expt.run()
            expt.__del__()
            print('   End')
            data = sig.decimate(rxd['rx0'] * 13.788,
                                oversamplingFactor,
                                ftype='fir',
                                zero_phase=True)
            dataAll = np.concatenate((dataAll, data), axis=0)
        elif plotSeq == 1:
            expt.plot_sequence()
            plt.show()
            expt.__del__()

    if plotSeq == 1:
        expt.plot_sequence()
        plt.show()
        expt.__del__()
    elif plotSeq == 0:
        data = np.reshape(dataAll, (nExTime, nReadout))
        plotData(data, rfExTime, tAdqReal)
        plotRabiFlop(data, rfExTime, tAdqReal)
        plt.show()
Пример #3
0
def main():

    torch.cuda.manual_seed(seed)
    cudnn.benchmark = CUDNN

    # model
    model = tiramisu.FCDenseNet57(in_channels=8, n_classes=N_CLASSES)
    model = model.cuda()
    # model = torch.nn.DataParallel(model).cuda()
    print('  + Number of params: {}'.format(
        sum([p.data.nelement() for p in model.parameters()])))
    model.apply(utils.weights_init)
    optimizer = optim.SGD(model.parameters(),
                          lr=LEARNING_RATE,
                          momentum=0.9,
                          weight_decay=0.0005)
    criterion = nn.NLLLoss2d().cuda()

    exp_path = EXPERIMENT + EXPNAME
    if os.path.exists(exp_path):
        shutil.rmtree(exp_path)

    exp = experiment.Experiment(EXPNAME, EXPERIMENT)
    exp.init()

    START_EPOCH = exp.epoch
    END_EPOCH = START_EPOCH + N_EPOCHS

    # for epoch in range(1):
    for epoch in range(1, END_EPOCH):

        since = time.time()

        # # ### Collect data ###
        # # # delete existing folder and old data
        if os.path.exists(res_root_path):
            shutil.rmtree(res_root_path)
        utils.collect_data(ori_train_base_rp, res_train_base_rp)
        utils.collect_data(ori_val_base_rp, res_val_base_rp)
        # data loader
        train_loader, val_loader = utils.data_loader_sig(res_root_path)

        # ### Train ###
        trn_loss, trn_err = utils.train_sig(model, train_loader, optimizer,
                                            criterion, epoch)
        print('Epoch {:d}: Train - Loss: {:.4f}\tErr: {:.4f}'.format(
            epoch, trn_loss, trn_err))
        time_elapsed = time.time() - since
        print('Train Time {:.0f}m {:.0f}s'.format(time_elapsed // 60,
                                                  time_elapsed % 60))

        ### val ###
        val_loss, val_err = utils.test_sig(model, val_loader, criterion, epoch)
        print('Val - Loss: {:.4f}, Error: {:.4f}'.format(val_loss, val_err))
        time_elapsed = time.time() - since
        print('Total Time {:.0f}m {:.0f}s\n'.format(time_elapsed // 60,
                                                    time_elapsed % 60))

        ### Save Metrics ###
        exp.save_history('train', trn_loss, trn_err)
        exp.save_history('val', val_loss, val_err)

        ### Checkpoint ###
        exp.save_weights(model, trn_loss, val_loss, trn_err, val_err)
        exp.save_optimizer(optimizer, val_loss)

        ## Early Stopping ##
        if (epoch - exp.best_val_loss_epoch) > MAX_PATIENCE:
            print(("Early stopping at epoch %d since no " +
                   "better loss found since epoch %.3").format(
                       epoch, exp.best_val_loss))
            break

        # adjust the learning rate according to SGD
        # every 4 times, lr *= 0.5
        if epoch % 4 == 0:
            utils.adjust_learning_rate(LEARNING_RATE, LR_DECAY, optimizer,
                                       epoch, DECAY_LR_EVERY_N_EPOCHS)

        exp.epoch += 1
Пример #4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--DATASET_PATH',
                        type=str,
                        default='/disk2/zhangni/davis/dataset/Objectness/')
    parser.add_argument('--EXPERIMENT',
                        type=str,
                        default='/disk2/zhangni/davis/result/TrainNet/')
    parser.add_argument('--N_EPOCHS', type=int, default=200)
    parser.add_argument('--MAX_PATIENCE', type=int, default=20)
    parser.add_argument('--batch_size', type=int, default=16)
    parser.add_argument('--seed', type=int, default=0)
    parser.add_argument('--N_CLASSES', type=int, default=10)
    parser.add_argument('--LEARNING_RATE', type=float, default=1e-2)
    parser.add_argument('--LR_DECAY', type=float, default=0.995)
    parser.add_argument('--DECAY_LR_EVERY_N_EPOCHS', type=int, default=1)
    parser.add_argument('--WEIGHT_DECAY', type=float, default=0.0001)
    parser.add_argument('--CUDNN', type=bool, default=True)
    args = parser.parse_args()

    torch.cuda.manual_seed(args.seed)
    cudnn.benchmark = args.CUDNN

    normalize = transforms.Normalize(mean=saliency.mean, std=saliency.std)
    train_joint_transformer = transforms.Compose([
        joint_transforms.JointResize((224)),
        joint_transforms.JointRandomHorizontalFlip()
    ])

    train_dset = saliency.Saliency(args.DATASET_PATH,
                                   'train',
                                   joint_transform=train_joint_transformer,
                                   transform=transforms.Compose([
                                       transforms.ToTensor(),
                                       normalize,
                                   ]))
    train_loader = torch.utils.data.DataLoader(train_dset,
                                               batch_size=args.batch_size,
                                               shuffle=True)

    test_joint_transforms = transforms.Compose(
        [joint_transforms.JointResize(224)])
    val_dset = saliency.Saliency(args.DATASET_PATH,
                                 'val',
                                 joint_transform=test_joint_transforms,
                                 transform=transforms.Compose(
                                     [transforms.ToTensor(), normalize]))
    val_loader = torch.utils.data.DataLoader(val_dset,
                                             batch_size=args.batch_size,
                                             shuffle=False)

    model = tiramisu.FCDenseNet57(n_classes=args.N_CLASSES)
    #model = model.cuda()
    model = torch.nn.DataParallel(model).cuda()
    print('  + Number of params: {}'.format(
        sum([p.data.nelement() for p in model.parameters()])))
    model.apply(utils.weights_init)
    optimizer = optim.SGD(model.parameters(),
                          lr=args.LEARNING_RATE,
                          momentum=0.9,
                          weight_decay=0.0005)
    criterion = nn.NLLLoss2d().cuda()

    exp_dir = args.EXPERIMENT + 'Objectness'
    if os.path.exists(exp_dir):
        shutil.rmtree(exp_dir)

    exp = experiment.Experiment('Objectness', args.EXPERIMENT)
    exp.init()

    START_EPOCH = exp.epoch
    END_EPOCH = START_EPOCH + args.N_EPOCHS

    for epoch in range(1, END_EPOCH):

        since = time.time()

        ### Train ###
        trn_loss, trn_err = utils.train(model, train_loader, optimizer,
                                        criterion, epoch)
        print('Epoch {:d}: Train - Loss: {:.4f}\tErr: {:.4f}'.format(
            epoch, trn_loss, trn_err))
        time_elapsed = time.time() - since
        print('Train Time {:.0f}m {:.0f}s'.format(time_elapsed // 60,
                                                  time_elapsed % 60))

        ### Test ###
        val_loss, val_err = utils.test(model, val_loader, criterion, epoch)
        print('Val - Loss: {:.4f}, Error: {:.4f}'.format(val_loss, val_err))
        time_elapsed = time.time() - since
        print('Total Time {:.0f}m {:.0f}s\n'.format(time_elapsed // 60,
                                                    time_elapsed % 60))

        ### Save Metrics ###
        exp.save_history('train', trn_loss, trn_err)
        exp.save_history('val', val_loss, val_err)

        ### Checkpoint ###
        exp.save_weights(model, trn_loss, val_loss, trn_err, val_err)
        exp.save_optimizer(optimizer, val_loss)

        ## Early Stopping ##
        if (epoch - exp.best_val_loss_epoch) > args.MAX_PATIENCE:
            print(("Early stopping at epoch %d since no " +
                   "better loss found since epoch %.3").format(
                       epoch, exp.best_val_loss))
            break

        # Adjust Lr ###--old method
        if epoch % 4 == 0:
            utils.adjust_learning_rate(args.LEARNING_RATE, args.LR_DECAY,
                                       optimizer, epoch,
                                       args.DECAY_LR_EVERY_N_EPOCHS)

        exp.epoch += 1
Пример #5
0
def main():
    parser = argparse.ArgumentParser(description='GEmb')

    parser.add_argument('--config-file',
                        type=str,
                        default='../models/config.pkl')
    parser.add_argument('--start-over', dest='start_over', action='store_true')
    parser.add_argument('--train-gemb', dest='train_gemb', action='store_true')

    parser.add_argument('--train-data-file',
                        type=str,
                        default='../data/train.pkl')
    parser.add_argument('--dev-data-file', type=str, default='../data/dev.pkl')
    parser.add_argument('--test-data-file',
                        type=str,
                        default='../data/test.pkl')

    parser.add_argument('--task',
                        type=str,
                        default='tagging',
                        choices=['tagging', 'classification'])
    parser.add_argument('--use-gemb', dest='use_gemb', action='store_true')
    parser.add_argument('--keep-prob', type=float, default=0.9)

    parser.add_argument('--dictfile', type=str, default='../data/dicts.pkl')
    parser.add_argument('--embed-dim', type=int, default=300)
    parser.add_argument('--hidden-dims',
                        type=int,
                        nargs='+',
                        default=[256, 256])

    parser.add_argument('--early-stop', action='store_true')
    parser.add_argument('--patience', type=int, default=5)
    parser.add_argument('--min-delta', type=float, default=0.01)

    parser.add_argument('--seed', type=int, default=23)
    parser.add_argument('--lr', type=float, default=0.1)
    parser.add_argument('--beta1', type=float, default=0.9)
    parser.add_argument('--beta2', type=float, default=0.99)
    parser.add_argument('--eps', type=float, default=1e-8)
    parser.add_argument('--clip-norm', type=float, default=1.0)
    parser.add_argument('--global-norm', type=float, default=5.0)

    parser.add_argument('--ckpt', type=str, default='../models/model')
    parser.add_argument('--max-ckpts', type=int, default=20)
    parser.add_argument('--batch-size', type=int, default=64)
    parser.add_argument('--max-steps', type=int, default=1000000)
    parser.add_argument('--gemb-steps', type=int, default=1000000)
    parser.add_argument('--print-interval', type=int, default=50)
    parser.add_argument('--save-interval', type=int, default=1000)

    args = parser.parse_args()

    dicts = pkl.load(open(args.dictfile, 'rb'))
    vocab_size = len(dicts['i2w'])
    num_class = len(dicts['i2t'])

    cfg = experiment.Config()
    if not args.start_over and os.path.exists(args.config_file):
        cfg.load(args.config_file)
    else:
        cfg.config = {
            'train_data_file': args.train_data_file,
            'dev_data_file': args.dev_data_file,
            'test_data_file': args.test_data_file,
            'task': args.task,
            'keep_prob': args.keep_prob,
            'vocab_size': vocab_size,
            'embed_dim': args.embed_dim,
            'hidden_dims': args.hidden_dims,
            'num_class': num_class,
            'early_stop': args.early_stop,
            'patience': args.patience,
            'min_delta': args.min_delta,
            'seed': args.seed,
            'lr': args.lr,
            'beta1': args.beta1,
            'beta2': args.beta2,
            'eps': args.eps,
            'clip_norm': args.clip_norm,
            'global_norm': args.global_norm,
            'ckpt': args.ckpt,
            'max_ckpts': args.max_ckpts,
            'batch_size': args.batch_size,
            'max_steps': args.max_steps,
            'gemb_steps': args.gemb_steps,
            'print_interval': args.print_interval,
            'save_interval': args.save_interval
        }

        if not os.path.isdir(os.path.dirname(args.config_file)):
            os.mkdir(os.path.dirname(args.config_file))
        cfg.save(args.config_file)

    exp = experiment.Experiment(cfg.config)
    if args.train_gemb:
        exp.train_gemb()
    else:
        exp.train(args.use_gemb)
        str(s.et_sample)
    ]


def write_output(o, filename='default'):
    '''Write list of lists to filename.'''
    if not filename.endswith('.txt'): filename += '.txt'
    print('Saving information to:', filename)
    fout = open(filename, 'w')
    fout.write('\n'.join(['\t'.join(line) for line in o]))
    fout.close()


# load structure (fid2ort) with start and end times of word / chunks / sentences
# prints errors to the screen
e = experiment.Experiment()

# create pp 1 object with a copy of fid2ort
e.add_participant(1)

# create ifadv session with start and end sample numbers for words and sentences
e.pp1.add_session('ifadv')

# print session info
print(e.pp1.sifadv)

# set pp_id and experiment name
pp_id = str(e.pp1.sifadv.pp_id)
exp = e.pp1.sifadv.exp_type

#create a list of sentence information
Пример #7
0
def saturationrecoveryStandalone(
        init_gpa=False,
        larmorFreq=3.077,  # MHz 
        rfExAmp=0.4,
        rfReAmp=0.4,
        rfExTime=20,  # us 
        rfReTime=20,  # us
        acqTime=4,  # ms
        echoTime=20,  # ms
        repetitionTime=5,  # s
        tSatIni=0.01,  # s
        tSatFin=0.9,  # s
        nRepetitions=1,  # number of samples
        nRD=100,
        plotSeq=0,
        shimming=[-70, -90, 10]):

    shimming = np.array(shimming) * 1e-4

    if rfReTime is None:
        rfReTime = 2 * rfExTime

    rfExTime = rfExTime * 1e-6
    rfReTime = rfReTime * 1e-6
    acqTime = acqTime * 1e-3
    echoTime = echoTime * 1e-3

    rawData = {}
    rawData['seqName'] = 'inversionRecovery'
    rawData['larmorFreq'] = larmorFreq * 1e6
    rawData['rfExAmp'] = rfExAmp
    rawData['rfReAmp'] = rfReAmp
    rawData['rfExTime'] = rfExTime
    rawData['rfRetime'] = rfReTime
    rawData['repetitionTime'] = repetitionTime
    rawData['tSatIni'] = tSatIni
    rawData['tSatFin'] = tSatFin
    rawData['nRepetitions'] = nRepetitions
    rawData['acqTime'] = acqTime
    rawData['nRD'] = nRD
    rawData['echoTime'] = echoTime

    # Miscellaneous
    gradRiseTime = 200  # us
    crusherTime = 1000  # us
    gSteps = int(gradRiseTime / 5)
    axes = np.array([0, 1, 2])
    rawData['gradRiseTime'] = gradRiseTime
    rawData['gSteps'] = gSteps

    # Bandwidth and sampling rate
    bw = nRD / acqTime * 1e-6  # MHz
    bwov = bw * hw.oversamplingFactor
    samplingPeriod = 1 / bwov

    tSat = np.geomspace(tSatIni, tSatFin, nRepetitions)
    rawData['tSat'] = tSat

    def createSequence():
        # Set shimming
        mri.iniSequence(expt, 20, shimming)

        for repeIndex in range(nRepetitions):
            # Initialize time
            tEx = 20e3 + np.max(tSat) + repetitionTime * repeIndex

            # Inversion time for current iteration
            inversionTime = tSat[repeIndex]

            # Crusher gradient for inversion rf pulse
            #            t0 = tEx-inversionTime-crusherTime/2-gradRiseTime-hw.gradDelay-50
            #            mri.gradTrap(expt, t0, gradRiseTime, crusherTime, 0.005, gSteps, axes[0], shimming)
            #            mri.gradTrap(expt, t0, gradRiseTime, crusherTime, 0.005, gSteps, axes[1], shimming)
            #            mri.gradTrap(expt, t0, gradRiseTime, crusherTime, 0.005, gSteps, axes[2], shimming)

            # Saturation pulse
            t0 = tEx - inversionTime - hw.blkTime - rfReTime / 2
            mri.rfRecPulse(expt, t0, rfReTime, rfReAmp, 0)

            # Spoiler gradients to destroy residual transversal signal detected for ultrashort inversion times
            #            mri.gradTrap(expt, t0+hw.blkTime+rfReTime, gradRiseTime, inversionTime*0.5, 0.005, gSteps, axes[0], shimming)
            #            mri.gradTrap(expt, t0+hw.blkTime+rfReTime, gradRiseTime, inversionTime*0.5, 0.005, gSteps, axes[1], shimming)
            #            mri.gradTrap(expt, t0+hw.blkTime+rfReTime, gradRiseTime, inversionTime*0.5, 0.005, gSteps, axes[2], shimming)

            # Excitation pulse
            t0 = tEx - hw.blkTime - rfExTime / 2
            mri.rfRecPulse(expt, t0, rfExTime, rfExAmp, 0)

            #            # Rx gating
            #            t0 = tEx+rfExTime/2+hw.deadTime
            #            mri.rxGate(expt, t0, acqTime)

            # Crusher gradient
            t0 = tEx + echoTime / 2 - crusherTime / 2 - gradRiseTime - hw.gradDelay - 50
            mri.gradTrap(expt, t0, gradRiseTime, crusherTime, 0.005, gSteps,
                         axes[0], shimming)
            mri.gradTrap(expt, t0, gradRiseTime, crusherTime, 0.005, gSteps,
                         axes[1], shimming)
            mri.gradTrap(expt, t0, gradRiseTime, crusherTime, 0.005, gSteps,
                         axes[2], shimming)

            # Refocusing pulse
            t0 = tEx + echoTime / 2 - rfReTime / 2 - hw.blkTime
            mri.rfRecPulse(expt, t0, rfReTime, rfReAmp, np.pi / 2)

            # Rx gating
            t0 = tEx + echoTime - acqTime / 2
            mri.rxGate(expt, t0, acqTime)

        # End sequence
        mri.endSequence(expt, scanTime)

    # Time variables in us
    rfExTime *= 1e6
    rfReTime *= 1e6
    repetitionTime *= 1e6
    echoTime *= 1e6
    tSat *= 1e6
    scanTime = nRepetitions * repetitionTime  # us

    expt = ex.Experiment(lo_freq=larmorFreq,
                         rx_t=samplingPeriod,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    samplingPeriod = expt.get_rx_ts()[0]  # us
    bw = 1 / samplingPeriod / hw.oversamplingFactor  # MHz
    acqTime = nRD / bw  # us
    rawData['samplingPeriod'] = samplingPeriod * 1e-6
    rawData['bw'] = bw * 1e6
    createSequence()

    # Representar Secuencia o tomar los datos.
    tSat1 = np.geomspace(tSatIni, tSatFin, nRepetitions)
    tSat2 = np.geomspace(tSatIni, tSatFin, 10 * nRepetitions)
    if plotSeq == 1:
        expt.plot_sequence()
        plt.show()
        expt.__del__()
    elif plotSeq == 0:
        print('Running...')
        rxd, msgs = expt.run()
        print('End')
        data = rxd['rx0'] * 13.788
        expt.__del__()
        data = sig.decimate(data,
                            hw.oversamplingFactor,
                            ftype='fir',
                            zero_phase=True)
        rawData['fullData'] = data
        dataIndiv = np.reshape(data, (nRepetitions, nRD))
        dataIndiv = np.real(
            dataIndiv[:, int(nRD / 2)] *
            np.exp(-1j * (np.angle(dataIndiv[0, int(nRD / 2)]) + np.pi)))
        results = np.transpose(np.array([tSat1,
                                         dataIndiv / np.max(dataIndiv)]))
        #        results = np.transpose(np.array([tSat1, dataIndiv]))
        rawData['signalVsTime'] = results

        plt.figure(1)
        plt.plot(np.abs(data))
        plt.show()

        # For 1 component
        fitData1, xxx = curve_fit(func1, results[:, 0], results[:, 1])
        print('For one component:')
        print('mA', round(fitData1[0], 1))
        print('T1', round(fitData1[1] * 1e3), ' ms')
        rawData['T11'] = fitData1[1] * 1e3
        rawData['M1'] = fitData1[0]

        # For 2 components
        fitData2, xxx = curve_fit(func2,
                                  results[:, 0],
                                  results[:, 1],
                                  p0=(1, 0.1, 0.5, 0.05),
                                  bounds=(0., 5.))
        print('For two components:')
        print('Ma', round(fitData2[0], 1))
        print('Mb', round(fitData2[2], 1))
        print('T1a', round(fitData2[1] * 1e3), ' ms')
        print('T1b', round(fitData2[3] * 1e3), ' ms')
        rawData['T12'] = [fitData2[1], fitData2[3]]
        rawData['M2'] = [fitData2[0], fitData2[2]]

        # For 3 components
        fitData3, xxx = curve_fit(func3,
                                  results[:, 0],
                                  results[:, 1],
                                  p0=(1, 0.1, 0.5, 0.05, 1, 0.01),
                                  bounds=(0., 5.))
        print('For three components:')
        print('Ma', round(fitData3[0], 1), ' ms')
        print('Mb', round(fitData3[2], 1), ' ms')
        print('Mc', round(fitData3[4], 1), ' ms')
        print('T1a', round(fitData3[1] * 1e3), ' ms')
        print('T1b', round(fitData3[3] * 1e3), ' ms')
        print('T1c', round(fitData3[5] * 1e3), ' ms')
        rawData['T13'] = [fitData3[1], fitData3[3], fitData3[5]]
        rawData['M3'] = [fitData3[0], fitData3[2], fitData3[4]]

        # Save data
        mri.saveRawData(rawData)

        # Plots
        plt.figure(2, figsize=(5, 5))
        plt.plot(results[:, 0], results[:, 1], 'o')
        plt.plot(tSat2, func1(tSat2, *fitData1))
        plt.plot(tSat2, func2(tSat2, *fitData2))
        plt.plot(tSat2, func3(tSat2, *fitData3))
        plt.title(rawData['fileName'])
        plt.xscale('log')
        plt.xlabel('t(s)')
        plt.ylabel('Signal (mV)')
        plt.legend([
            'Experimental', 'Fitting 1 component', 'Fitting 2 components',
            'Fitting 3 components'
        ])
        plt.title(rawData['fileName'])
        plt.show()
Пример #8
0
 def single_experiment_sim(self):
     t = track.Track(track=self.track_json)
     e = experiment.Experiment(track=t, brain_pop=self.population)
     e.run()
     results = e.experiment_results()
     print("Fitness results" + "\n".join([x[0] + x[1] for x in results]))
Пример #9
0
def flipAngle(self):

    lo_freq = self.lo_freq  # KHz
    rf_amp = self.rf_amp  # 1 = full-scale
    N = self.N
    step = self.step
    rf_pi2_duration = self.rf_pi2_duration
    echo_duration = self.echo_duration * 1e3
    BW = self.BW  # us, 3.333us, 300 kHz rate
    rx_wait = self.rx_wait * 1e3
    readout_duration = self.readout_duration * 1e3
    tr_duration = self.tr_duration * 1e3
    nScans = self.nScans

    rx_period = 1 / (BW * 1e-3)
    rf_pi_duration = 2 * rf_pi2_duration

    ## All times are in the context of a single TR, starting at time 0
    init_gpa = False

    tx_gate_pre = 2  # us, time to start the TX gate before the RF pulse begins
    tx_gate_post = 1  # us, time to keep the TX gate on after the RF pulse ends
    tstart = 20
    pi2_phase = 1  # x
    pi_phase = 1j  # y

    expt = ex.Experiment(lo_freq=lo_freq,
                         rx_t=rx_period,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    i = 0

    amps = np.linspace(rf_amp - N / 2 * step, rf_amp + N / 2 * step, N)
    while i < N:
        rf_tend = tstart + echo_duration + rf_pi_duration / 2  # us
        rx_tstart = rf_tend + rx_wait  # us
        rx_tend = rx_tstart + readout_duration  # us
        expt.add_flodict({
            # second tx0 pulse purely for loopback debugging
            'tx0': (np.array([
                tstart + (echo_duration - rf_pi2_duration) / 2,
                tstart + (echo_duration + rf_pi2_duration) / 2,
                tstart + echo_duration - rf_pi_duration / 2, rf_tend
            ]), np.array([pi2_phase * amps[i], 0, pi_phase * amps[i], 0])),
            'rx0_en': (np.array([rx_tstart, rx_tend]), np.array([1, 0])),
            'tx_gate': (np.array([
                tstart + (echo_duration - rf_pi2_duration) / 2 - tx_gate_pre,
                tstart + (echo_duration + rf_pi2_duration) / 2 + tx_gate_post,
                tstart + echo_duration - rf_pi_duration / 2 - tx_gate_pre,
                rf_tend + tx_gate_post
            ]), np.array([1, 0, 1, 0])),
            'rx_gate': (np.array([rx_tstart, rx_tend]), np.array([1, 0]))
        })

        i = i + 1
        tstart = tstart + tr_duration

    for nS in range(nScans):
        print('nScan=%s' % (nS))
        rxd, msgs = expt.run()
        if nS == 0:
            n_rxd = rxd['rx0']
        else:
            n_rxd = np.concatenate((n_rxd, rxd['rx0']), axis=0)

    n_rxd = np.reshape(n_rxd, (nScans, len(rxd['rx0'])))
    n_rxd = np.average(n_rxd, axis=0)

    expt.__del__()
    return n_rxd, msgs, amps
Пример #10
0
#!/usr/bin/python
#-*- coding: utf-8 -*-

__author__ = 'rupy'

import logging
import experiment

if __name__=="__main__":
    logging.root.setLevel(level=logging.INFO)

    ex = experiment.Experiment(False)
    ex.process_features()

    # ex.fit_changing_sample_num(sample_num_list=[2000, 1500, 1000, 500])
    #
    # ex.calc_accuracy_changing_sample_num(sample_num_list=[2000, 1500, 1000, 500])

    sample_list = range(20, 501, 20)

    ex.fit_changing_sample_num(sample_num_list=sample_list)

    res_cca, res_gcca = ex.calc_accuracy_changing_sample_num(sample_num_list=sample_list)
    ex.plot_results(res_cca, res_gcca, sample_list, 5)
    ex.plot_result(sample_num=500, reg_param=0.1)

Пример #11
0
def larmor(lo_freq=3.023, # MHz
             rf_amp=0.62, # 1 = full-scale
             rf_pi2_duration=50,
             N_larmor=5,  # Number of points
             step=1e-3,  # Step in Khz
             rx_wait = 100,   #us
             BW=31,  # us, 3.333us, 300 kHz rate
             readout_duration=5000,
             echo_duration=4,   #ms
             ):

           

    rx_period = 1/(BW*1e-3)
    echo_duration = echo_duration*1e3

    rf_pi_duration = 2*rf_pi2_duration
    BW = 1e-3   
       
    ## All times are in the context of a single TR, starting at time 0
    init_gpa = False
   
    tx_gate_pre = 2 # us, time to start the TX gate before the RF pulse begins
    tx_gate_post = 1 # us, time to keep the TX gate on after the RF pulse ends
    tstart = 0   
    pi2_phase = 1 # x
    pi_phase = 1j # y
    
    i=0
    peakValsf = []
    freqs = np.linspace(lo_freq-N_larmor/2*step, lo_freq+N_larmor/2*step, N_larmor)
    
    while i<N_larmor:
    
        expt = ex.Experiment(lo_freq=freqs[i], rx_t=rx_period, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    
        rf_tend = tstart+echo_duration+rf_pi_duration/2 # us
        rx_tstart = rf_tend+rx_wait # us
        rx_tend = rx_tstart + readout_duration  # us
        expt.add_flodict({
            # second tx0 pulse purely for loopback debugging
            'tx0': (np.array([tstart + (echo_duration - rf_pi2_duration)/2, tstart + (echo_duration + rf_pi2_duration)/2,
                         tstart + echo_duration - rf_pi_duration/2, rf_tend]), np.array([pi2_phase*rf_amp, 0, pi_phase*rf_amp, 0])),
            'rx0_en': ( np.array([rx_tstart, rx_tend]),  np.array([1, 0]) ),
            'tx_gate': (np.array([tstart + (echo_duration - rf_pi2_duration)/2- tx_gate_pre, tstart + (echo_duration + rf_pi2_duration)/2 + tx_gate_post,
                         tstart + echo_duration - rf_pi_duration/2- tx_gate_pre, rf_tend+ tx_gate_post]), np.array([1, 0, 1, 0])),
            'rx_gate': ( np.array([rx_tstart, rx_tend]), np.array([1, 0]) )
        })
    
        rxd, msg = expt.run()    
        dataobject:DataManager=DataManager(rxd['rx0'], freqs[i], len(rxd['rx0']), [], BW)
        f_signalValue, t_signalValue, f_signalIdx, f_signalFrequency = dataobject.get_peakparameters()
        peakValsf.append(f_signalValue)
        
        expt.__del__()

        print(i)
        i = i+1
        
    
    
    return(peakValsf)
Пример #12
0
def gre_standalone(
    init_gpa=False,              # Starts the gpa
    nScans = 1,                 # NEX
    larmorFreq = 3.0797e6,      # Larmor frequency
    rfExAmp = 0.05,             # rf excitation pulse amplitude
    rfExTime = 30e-6,          # rf excitation pulse time
    echoTime = 2e-3,              # TE
    repetitionTime = 10e-3,     # TR
    fov = np.array([13e-2, 13e-2, 13e-2]),           # FOV along readout, phase and slice
    dfov = np.array([0e-3, 2e-3, -5e-3]),            # Displacement of fov center
    nPoints = np.array([60, 60, 1]),                 # Number of points along readout, phase and slice
    acqTime = 1e-3,             # Acquisition time
    axes = np.array([1, 2, 0]),       # 0->x, 1->y and 2->z defined as [rd,ph,sl]
    axesEnable = np.array([1, 1, 0]), # 1-> Enable, 0-> Disable
    dephaseGradTime = 1000e-6,       # Phase and slice dephasing time
    rdPreemphasis = 1.0,                               # Preemphasis factor for readout dephasing
    drfPhase = 0,                           # phase of the excitation pulse (in degrees)
    dummyPulses = 20,                     # Dummy pulses for T1 stabilization
    shimming = np.array([-80, -100, 10]),       # Shimming along the X,Y and Z axes (a.u. *1e4)
    parAcqLines = 0,                         # Number of additional lines, Full sweep if 0
    plotSeq = 1):
    
    # rawData fields
    rawData = {}
    
    # Miscellaneous
    blkTime = 1             # Deblanking time (us)
    larmorFreq = larmorFreq*1e-6
    gradRiseTime = 100e-6       # Estimated gradient rise time
    gradDelay = 9            # Gradient amplifier delay
    addRdPoints = 5             # Initial rd points to avoid artifact at the begining of rd
    gammaB = 42.56e6            # Gyromagnetic ratio in Hz/T
    oversamplingFactor = 6
    addRdGradTime = 200e-6     # Additional readout gradient time to avoid turn on/off effects on the Rx channel
    shimming = shimming*1e-4
    rawData['gradDelay'] = gradDelay*1e-6
    rawData['gradRiseTime'] = gradRiseTime
    rawData['oversamplingFactor'] = oversamplingFactor
    rawData['addRdGradTime'] = addRdGradTime*1e-6
    
    # Matrix size
    nRD = nPoints[0]+2*addRdPoints
    nPH = nPoints[1]*axesEnable[1]+(1-axesEnable[1])
    nSL = nPoints[2]*axesEnable[2]+(1-axesEnable[2])
    nPoints[1] = nPH
    nPoints[2] = nSL
    
    # rawData for rawData
    rawData['nScans'] = nScans
    rawData['larmorFreq'] = larmorFreq      # Larmor frequency
    rawData['rfExAmp'] = rfExAmp             # rf excitation pulse amplitude
    rawData['rfExTime'] = rfExTime          # rf excitation pulse time
    rawData['echoTime'] = echoTime        # TE
    rawData['repetitionTime'] = repetitionTime     # TR
    rawData['fov'] = fov           # FOV along readout, phase and slice
    rawData['dfov'] = dfov            # Displacement of fov center
    rawData['nPoints'] = nPoints                 # Number of points along readout, phase and slice
    rawData['acqTime'] = acqTime             # Acquisition time
    rawData['axes'] = axes       # 0->x, 1->y and 2->z defined as [rd,ph,sl]
    rawData['axesEnable'] = axesEnable # 1-> Enable, 0-> Disable
    rawData['phaseGradTime'] = dephaseGradTime       # Phase and slice dephasing time
    rawData['rdPreemphasis'] = rdPreemphasis
    rawData['drfPhase'] = drfPhase 
    rawData['dummyPulses'] = dummyPulses                    # Dummy pulses for T1 stabilization
    rawData['shimming'] = shimming
    rawData['parAcqLines'] = parAcqLines
    
    # parAcqLines in case parAcqLines = 0
    if parAcqLines==0:
        parAcqLines = int(nSL/2)
    
    # BW
    BW = nPoints[0]/acqTime*1e-6
    BWov = BW*oversamplingFactor
    samplingPeriod = 1/BWov
    
    # Readout rephasing time
    rdRephTime = acqTime+2*addRdGradTime
    
    # Check if dephasing grad time is ok
    maxDephaseGradTime = echoTime-(rfExTime+rdRephTime)-3*gradRiseTime
    if dephaseGradTime==0 or dephaseGradTime>maxDephaseGradTime:
        dephaseGradTime = maxDephaseGradTime
    
    # Max gradient amplitude
    rdGradAmplitude = nPoints[0]/(gammaB*fov[0]*acqTime)*axesEnable[0]
    rdDephGradAmplitude = -rdGradAmplitude*(rdRephTime+gradRiseTime)/(2*(dephaseGradTime+gradRiseTime))
    phGradAmplitude = nPH/(2*gammaB*fov[1]*(dephaseGradTime+gradRiseTime))*axesEnable[1]
    slGradAmplitude = nSL/(2*gammaB*fov[2]*(dephaseGradTime+gradRiseTime))*axesEnable[2]

    # Phase and slice gradient vector
    phGradients = np.linspace(-phGradAmplitude,phGradAmplitude,num=nPH,endpoint=False)
    slGradients = np.linspace(-slGradAmplitude,slGradAmplitude,num=nSL,endpoint=False)
    rawData['phGradients'] = phGradients
    rawData['slGradients'] = slGradients
    
    # Change gradient values to OCRA units
    gFactor = reorganizeGfactor(axes)
    rdGradAmplitude = rdGradAmplitude/gFactor[0]*1000/5
    rdDephGradAmplitude = rdDephGradAmplitude/gFactor[0]*1000/5
    phGradAmplitude = phGradAmplitude/gFactor[1]*1000/5
    slGradAmplitude = slGradAmplitude/gFactor[2]*1000/5
    phGradients = phGradients/gFactor[1]*1000/5
    slGradients = slGradients/gFactor[2]*1000/5
    if np.abs(rdGradAmplitude)>1:
        return(0)
    if np.abs(rdDephGradAmplitude)>1:
        return(0)
    if np.abs(phGradAmplitude)>1 or np.abs(slGradAmplitude)>1:
        return(0)
    
    # Initialize the experiment
    expt = ex.Experiment(lo_freq=larmorFreq, rx_t=samplingPeriod, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    samplingPeriod = expt.get_rx_ts()[0]
    BW = 1/samplingPeriod/oversamplingFactor
    acqTime = nPoints[0]/BW        # us
    rawData['bandwidth'] = BW*1e6
    
    # Create an rf pulse function
    def rfPulse(tStart,rfTime,rfAmplitude,rfPhase):
        txTime = np.array([tStart+blkTime,tStart+blkTime+rfTime])
        txAmp = np.array([rfAmplitude*np.exp(1j*rfPhase),0.])
        txGateTime = np.array([tStart,tStart+blkTime+rfTime])
        txGateAmp = np.array([1,0])
        expt.add_flodict({
            'tx0': (txTime, txAmp),
            'tx_gate': (txGateTime, txGateAmp)
            })

    # Readout function
    def rxGate(tStart,gateTime):
        rxGateTime = np.array([tStart,tStart+gateTime])
        rxGateAmp = np.array([1,0])
        expt.add_flodict({
            'rx0_en':(rxGateTime, rxGateAmp), 
            'rx_gate': (rxGateTime, rxGateAmp), 
            })

    # Gradients
    def gradPulse(tStart, gTime, gAmp,  gAxes):
        t = np.array([tStart, tStart+gradRiseTime+gTime])
        a = np.array([gAmp, 0])
        if gAxes==0:
            expt.add_flodict({'grad_vx': (t, a+shimming[0])})
        elif gAxes==1:
            expt.add_flodict({'grad_vy': (t, a+shimming[1])})
        elif gAxes==2:
            expt.add_flodict({'grad_vz': (t, a+shimming[2])})
    
    def endSequence(tEnd):
        expt.add_flodict({
                'grad_vx': (np.array([tEnd]),np.array([0]) ), 
                'grad_vy': (np.array([tEnd]),np.array([0]) ), 
                'grad_vz': (np.array([tEnd]),np.array([0]) ),
             })
             
    def iniSequence(tEnd):
        expt.add_flodict({
                'grad_vx': (np.array([tEnd]),np.array([shimming[0]]) ), 
                'grad_vy': (np.array([tEnd]),np.array([shimming[1]]) ), 
                'grad_vz': (np.array([tEnd]),np.array([shimming[2]]) ),
             })

    # Changing time parameters to us
    rfExTime = rfExTime*1e6
    echoTime = echoTime*1e6
    repetitionTime = repetitionTime*1e6
    gradRiseTime = gradRiseTime*1e6
    dephaseGradTime = dephaseGradTime*1e6
    rdRephTime = rdRephTime*1e6
    addRdGradTime = addRdGradTime*1e6
    
    # Create sequence instructions
    phIndex = 0
    slIndex = 0
    scanTime = (nPH*nSL+dummyPulses)*repetitionTime
    nRepetitions = nPH*nSL+dummyPulses
    # Set shimming
    iniSequence(20)
    for repeIndex in range(nRepetitions):
        # Initialize time
        t0 = 20+repetitionTime*repeIndex
        
        # Excitation pulse
        rfPulse(t0,rfExTime,rfExAmp,drfPhase*np.pi/180)
    
        # Dephasing gradients
        t0 += blkTime+rfExTime-gradDelay
        gradPulse(t0, dephaseGradTime, rdDephGradAmplitude*rdPreemphasis, axes[0])
        gradPulse(t0, dephaseGradTime, phGradients[phIndex], axes[1])
        gradPulse(t0, dephaseGradTime, slGradients[slIndex], axes[2])
        
        # Rephasing readout gradient
        t0 = 20+repetitionTime*repeIndex+blkTime+rfExTime/2+echoTime-rdRephTime/2-gradRiseTime-gradDelay
        gradPulse(t0, rdRephTime, rdGradAmplitude, axes[0])
        
        # Rx gate
        t0 += gradDelay+gradRiseTime+addRdGradTime-addRdPoints/BW
        if repeIndex>=dummyPulses:         # This is to account for dummy pulses
            rxGate(t0, acqTime+2*addRdPoints/BW)
        
        # Spoiler
        t0 += acqTime+2*addRdPoints/BW+addRdGradTime+gradRiseTime
        gradPulse(t0, dephaseGradTime, -rdDephGradAmplitude*rdPreemphasis, axes[0])
        gradPulse(t0, dephaseGradTime, phGradients[phIndex], axes[1])
        gradPulse(t0, dephaseGradTime, slGradients[slIndex], axes[2])
        
        # Update the phase and slice gradient
        if repeIndex>=dummyPulses:
            if phIndex == nPH-1:
                phIndex = 0
                slIndex += 1
            else:
                phIndex += 1
        
        if repeIndex == nRepetitions:
            endSequence(scanTime)
    
    # Plot sequence:
    if plotSeq==1:
        expt.plot_sequence()
    
    # Run the experiment
    dataFull = []
    for ii in range(nScans):
        rxd, msgs = expt.run()
        rxd['rx0'] = rxd['rx0']*13.788   # Here I normalize to get the result in mV
        # Get data
        scanData = sig.decimate(rxd['rx0'], oversamplingFactor, ftype='fir', zero_phase=True)
        dataFull = np.concatenate((dataFull, scanData), axis = 0)
    # Delete experiment:
    expt.__del__()
    
    # Delete the addRdPoints
#    nPoints[0] = nRD
    dataFull = np.reshape(dataFull, (nPH*nSL*nScans, nRD))
    dataFull = dataFull[:, addRdPoints:addRdPoints+nPoints[0]]
    dataFull = np.reshape(dataFull, (1, nPoints[0]*nPH*nSL*nScans))
    
    # Average data
    data = np.reshape(dataFull, (nScans, nPoints[0]*nPH*nSL))
    data = np.average(data, axis=0)
    data = np.reshape(data, (nSL, nPH, nPoints[0]))
    
    # Do zero padding
    dataTemp = data
    data = np.zeros((nPoints[2], nPoints[1], nPoints[0]))
    data = data+1j*data
    if nSL==1:
        data = dataTemp
    else:
        data[0:nSL-1, :, :] = dataTemp[0:nSL-1, :, :]
    data = np.reshape(data, (1, nPoints[0]*nPoints[1]*nPoints[2]))
        
    # Fix the position of the sample according t dfov
    kMax = nPoints/(2*fov)*axesEnable
    kRD = np.linspace(-kMax[0],kMax[0],num=nPoints[0],endpoint=False)
    kPH = np.linspace(-kMax[1],kMax[1],num=nPH,endpoint=False)
    kSL = np.linspace(-kMax[2],kMax[2],num=nSL,endpoint=False)
    kPH = kPH[::-1]
    kPH, kSL, kRD = np.meshgrid(kPH, kSL, kRD)
    kRD = np.reshape(kRD, (1, nPoints[0]*nPH*nSL))
    kPH = np.reshape(kPH, (1, nPoints[0]*nPH*nSL))
    kSL = np.reshape(kSL, (1, nPoints[0]*nPH*nSL))
    dPhase = np.exp(-2*np.pi*1j*(dfov[0]*kRD+dfov[1]*kPH+dfov[2]*kSL))
    data = data*dPhase
    
    # Create sampled data
    kRD = np.reshape(kRD, (nPoints[0]*nPoints[1]*nPoints[2], 1))
    kPH = np.reshape(kPH, (nPoints[0]*nPoints[1]*nPoints[2], 1))
    kSL = np.reshape(kSL, (nPoints[0]*nPoints[1]*nPoints[2], 1))
    data = np.reshape(data, (nPoints[0]*nPoints[1]*nPoints[2], 1))
    rawData['kMax'] = kMax
    rawData['sampled'] = np.concatenate((kRD, kPH, kSL, data), axis=1)

    # Get image with FFT
    data = np.reshape(data, (nSL, nPH, nPoints[0]))
    img=np.fft.ifftshift(np.fft.ifftn(np.fft.ifftshift(data)))
    rawData['image'] = img
    
    # Plot provisional image
#    plt.figure(1, figsize=(12, 6), dpi=80)
#    tVector = np.linspace(-acqTime/2, acqTime/2, num=nPoints[0],endpoint=False)*1e-3
#    for ii in range(nPH):
#        plt.subplot(1, 2, 1)
#        plt.plot(tVector, np.abs(data[0, ii, :]))
#        plt.xlabel('Time (ms)')
#        plt.ylabel('Signal (mV)')
#        
#        plt.subplot(1, 2, 2)
#        plt.plot(tVector, np.angle(data[0, ii, :]))
#        plt.ylim([-np.pi, np.pi])
#        plt.xlabel('Time (ms)')
#        plt.ylabel('Phase (rad)')
    
    
    
    # Plot data for 1D case
    if (nPH==1 and nSL==1):
        # Plot k-space
        plt.figure(2)
        dataPlot = data[0, 0, :]
        plt.subplot(1, 2, 1)
        if axesEnable[0]==0:
            tVector = np.linspace(-acqTime/2, acqTime/2, num=nPoints[0],endpoint=False)*1e-3
            sMax = np.max(np.abs(dataPlot))
            indMax = np.argmax(np.abs(dataPlot))
            timeMax = tVector[indMax]
            sMax3 = sMax/3
            dataPlot3 = np.abs(np.abs(dataPlot)-sMax3)
            indMin = np.argmin(dataPlot3)
            timeMin = tVector[indMin]
            T2 = np.abs(timeMax-timeMin)
            plt.plot(tVector, np.abs(dataPlot))
            plt.plot(tVector, np.real(dataPlot))
            plt.plot(tVector, np.imag(dataPlot))
            plt.xlabel('t (ms)')
            plt.ylabel('Signal (mV)')
            print(T2)
        else:
            plt.plot(kRD[0, :], np.abs(dataPlot))
            plt.yscale('log')
            plt.xlabel('krd (mm^-1)')
            plt.ylabel('Signal (mV)')
        # Plot image
        plt.subplot(122)
        img = img[0, 0, :]
        if axesEnable[0]==0:
            xAxis = np.linspace(-BW/2, BW/2, num=nPoints[0], endpoint=False)*1e3
            plt.plot(xAxis, np.abs(img), '.')
            plt.xlabel('Frequency (kHz)')
            plt.ylabel('Density (a.u.)')
            print(np.max(np.abs(img)))
        else:
            xAxis = np.linspace(-fov[0]/2*1e2, fov[0]/2*1e2, num=nPoints[0], endpoint=False)
            plt.plot(xAxis, np.abs(img))
            plt.xlabel('Position RD (cm)')
            plt.ylabel('Density (a.u.)')
    else:
        # Plot k-space
        plt.figure(2)
        dataPlot = data[round(nSL/2), :, :]
        plt.subplot(131)
        plt.imshow(np.log(np.abs(dataPlot)),cmap='gray')
        plt.title('k-Space')
        plt.axis('off')
        # Plot image
        imgPlot = img[round(nSL/2), :, :]
        plt.subplot(132)
        plt.imshow(np.abs(imgPlot), cmap='gray')
        plt.axis('off')
        plt.title('Image magnitude')
        
        plt.subplot(133)
        plt.imshow(np.angle(imgPlot), cmap='gray')
        plt.axis('off')
        plt.title('Image phase')
        
#        fig = plt.figure(3)
#        img2Darg = np.angle(imgPlot)
#        X = np.arange(-1, 1, 2/(np.size(imgPlot, 1)))
#        Y = np.arange(-1, 1, 2/(np.size(imgPlot, 0)))
#        X,  Y = np.meshgrid(X, Y)
#        ax = fig.gca(projection='3d')
#        surf = ax.plot_surface(X, Y, img2Darg)
    
    # Save data
    dt = datetime.now()
    dt_string = dt.strftime("%Y.%m.%d.%H.%M.%S")
    dt2 = date.today()
    dt2_string = dt2.strftime("%Y.%m.%d")
    if not os.path.exists('experiments/acquisitions/%s' % (dt2_string)):
        os.makedirs('experiments/acquisitions/%s' % (dt2_string))
            
    if not os.path.exists('experiments/acquisitions/%s/%s' % (dt2_string, dt_string)):
        os.makedirs('experiments/acquisitions/%s/%s' % (dt2_string, dt_string)) 
    rawData['name'] = "%s.%s.mat" % ("GRE",dt_string)
    savemat("experiments/acquisitions/%s/%s/%s.%s.mat" % (dt2_string, dt_string, "GRE",dt_string),  rawData)
    print(rawData['name'])
    plt.show()
#!/usr/local/bin/python

#python Version 2.7.2
import numpy as np
import experiment as exp
import optimize as opt
import glob as gb

#Define which design to calculate
designDir = './Designs/V2_dichroic/'
plotInMM = True

#Define the atmosphere
atmFile = './Atacama_1000um_60deg.txt'

#Gather experiments
#designDirs  = sorted(gb.glob(designDir+'/*/'))
designDirs  = sorted(gb.glob(designDir+'/MF_45cm_7waf_silicon/'))
experiments = [exp.Experiment(dir, atmFile) for dir in designDirs]

#Optimize pixel sizes
optimizes   = [opt.Optimize(experiment) for experiment in experiments]
for optimize in optimizes: optimize.optimizeFP(plotInMM)
Пример #14
0
        def run(learning_rate, freeze_interval, num_hidden, reg):
            room_size = 5
            num_rooms = 2
            mdp = mdps.MazeMDP(room_size, num_rooms)
            mdp.compute_states()
            mdp.EXIT_REWARD = 1
            mdp.MOVE_REWARD = -0.01
            discount = 1
            num_actions = len(mdp.get_actions(None))
            batch_size = 100
            print 'building network...'
            network = qnetwork.QNetwork(input_shape=2 * room_size +
                                        num_rooms**2,
                                        batch_size=batch_size,
                                        num_hidden_layers=2,
                                        num_actions=4,
                                        num_hidden=num_hidden,
                                        discount=discount,
                                        learning_rate=learning_rate,
                                        regularization=reg,
                                        update_rule='adam',
                                        freeze_interval=freeze_interval,
                                        rng=None)
            num_epochs = 50
            epoch_length = 2
            test_epoch_length = 0
            max_steps = 4 * (room_size * num_rooms)**2
            epsilon_decay = (num_epochs * epoch_length * max_steps) / 1.5
            print 'building policy...'
            p = policy.EpsilonGreedy(num_actions, 0.5, 0.05, epsilon_decay)
            print 'building memory...'
            rm = replay_memory.ReplayMemory(batch_size, capacity=50000)
            print 'building logger...'
            log = logger.NeuralLogger(agent_name='QNetwork')
            print 'building state adapter...'
            adapter = state_adapters.CoordinatesToRowColRoomAdapter(
                room_size=room_size, num_rooms=num_rooms)
            # adapter = state_adapters.CoordinatesToRowColAdapter(room_size=room_size, num_rooms=num_rooms)
            # adapter = state_adapters.CoordinatesToFlattenedGridAdapter(room_size=room_size, num_rooms=num_rooms)
            # adapter = state_adapters.IdentityAdapter(room_size=room_size, num_rooms=num_rooms)
            # adapter = state_adapters.CoordinatesToSingleRoomRowColAdapter(room_size=room_size)
            print 'building agent...'
            a = agent.NeuralAgent(network=network,
                                  policy=p,
                                  replay_memory=rm,
                                  log=log,
                                  state_adapter=adapter)
            run_tests = False
            e = experiment.Experiment(mdp,
                                      a,
                                      num_epochs,
                                      epoch_length,
                                      test_epoch_length,
                                      max_steps,
                                      run_tests,
                                      value_logging=True)
            e.run()

            ak = file_utils.load_key('../access_key.key')
            sk = file_utils.load_key('../secret_key.key')
            bucket = 'hierarchical'
            try:
                aws_util = aws_s3_utility.S3Utility(ak, sk, bucket)
                aws_util.upload_directory(e.agent.logger.log_dir)
            except Exception as e:
                print 'error uploading to s3: {}'.format(e)
Пример #15
0
from nettack import sbm
import scipy.sparse as sp
import experiment
import warnings

warnings.filterwarnings("ignore")
gpu_id = None  # set this to your desired GPU ID if you want to use GPU computations (only for the GCN/surrogate training)
#One can also repeat the experiment with the dataset cora.

#datasets=['citeseer', 'cora']
datasets = ['cora']
#community=range(num_communities)
strong = True
n = 2
for dataset in datasets:
    exp = experiment.Experiment(dataset, gpu_id=gpu_id)
    exp.compute_p_hat()
    #communities=[]
    #for i in range(exp._K):
    #    communities.append([i])
    communities = []
    if dataset is 'cora':
        #communities.append(list([2]))
        communities.append(list([4]))
    else:
        communities.append(list([0]))
        communities.append(list([1]))
        communities.append(list([3]))

    for community in communities:
        for strong in [True, False]:
#!/usr/local/bin/python

#python Version 2.7.2
import numpy as np
import experiment as exp
import optimize as opt
import glob as gb

#Define the atmosphere
atmFile = './Atacama_1000um_60deg.txt'

#Gather experiments
designDirs  = sorted(gb.glob('./Designs/*'))
experiments = [exp.Experiment(dir) for dir in designDirs]

#Optimize pixel sizes
optimizes   = [opt.Optimize(experiment) for experiment in experiments]
for optimize in optimizes: optimize.optimizeFP()
Пример #17
0
        def run(learning_rate, freeze_interval, num_hidden, reg, seq_len, eps,
                nt, update):
            room_size = 5
            num_rooms = 2
            input_shape = 2 * room_size
            print 'building mdp...'
            mdp = mdps.MazeMDP(room_size, num_rooms)
            mdp.compute_states()
            mdp.EXIT_REWARD = 1
            mdp.MOVE_REWARD = -0.01
            network_type = nt
            discount = 1
            sequence_length = seq_len
            num_actions = len(mdp.get_actions(None))
            batch_size = 100
            update_rule = update
            print 'building network...'
            network = recurrent_qnetwork.RecurrentQNetwork(
                input_shape=input_shape,
                sequence_length=sequence_length,
                batch_size=batch_size,
                num_actions=4,
                num_hidden=num_hidden,
                discount=discount,
                learning_rate=learning_rate,
                regularization=reg,
                update_rule=update_rule,
                freeze_interval=freeze_interval,
                network_type=network_type,
                rng=None)

            # take this many steps because (very loosely):
            # let l be the step length
            # let d be the difference in start and end locations
            # let N be the number of steps for the agent to travel a distance d
            # then N ~ (d/l)^2  // assuming this is a random walk
            # with l = 1, this gives d^2 in order to make it N steps away
            # the desired distance here is to walk along both dimensions of the maze
            # which is equal to two times the num_rooms * room_size
            # so squaring that gives a loose approximation to the number of
            # steps needed (discounting that this is actually a lattice (does it really matter?))
            # (also discounting the walls)
            # see: http://mathworld.wolfram.com/RandomWalk2-Dimensional.html
            max_steps = (2 * room_size * num_rooms)**2
            num_epochs = 500
            epoch_length = 1
            test_epoch_length = 0
            epsilon_decay = (num_epochs * epoch_length * max_steps) / 4
            print 'building adapter...'
            adapter = state_adapters.CoordinatesToSingleRoomRowColAdapter(
                room_size=room_size)
            print 'building policy...'
            p = policy.EpsilonGreedy(num_actions, eps, 0.05, epsilon_decay)
            print 'building replay memory...'
            # want to track at minimum the last 50 episodes
            capacity = max_steps * 50
            rm = replay_memory.SequenceReplayMemory(
                input_shape=input_shape,
                sequence_length=sequence_length,
                batch_size=batch_size,
                capacity=capacity)
            print 'building logger...'
            log = logger.NeuralLogger(agent_name=network_type)
            print 'building agent...'
            a = agent.RecurrentNeuralAgent(network=network,
                                           policy=p,
                                           replay_memory=rm,
                                           log=log,
                                           state_adapter=adapter)
            run_tests = False
            print 'building experiment...'
            e = experiment.Experiment(mdp,
                                      a,
                                      num_epochs,
                                      epoch_length,
                                      test_epoch_length,
                                      max_steps,
                                      run_tests,
                                      value_logging=True)
            print 'running experiment...'
            e.run()

            ak = file_utils.load_key('../access_key.key')
            sk = file_utils.load_key('../secret_key.key')
            bucket = 'hierarchical9'
            try:
                aws_util = aws_s3_utility.S3Utility(ak, sk, bucket)
                aws_util.upload_directory(e.agent.logger.log_dir)
            except Exception as e:
                print 'error uploading to s3: {}'.format(e)
Пример #18
0
def noiseStandalone(
    nReadout =2500,
    BW = 500):

    init_gpa= False
    plotSeq = 0
    larmorFreq = 3.00
    oversamplingFactor=6
    BW=BW*1e-3
    if nReadout%2==0:
        nReadout = nReadout+1
    nPoints = np.array([nReadout, 1,1])
    

    #ARRAY INITIALIZATIONS 
    rxTime = []
    rxAmp = []
    dataAll  =[]
    
    # RAWDATA FIELDS
    rawData = {}
    rawData['larmorFreq'] = larmorFreq   
    rawData['nReadout'] = nReadout
    rawData['BW'] = BW
    
    # RX PULSE
    def readoutGate(tRef,tRd,rxTimePrevious,  rxAmpPrevious):
        rxTime = np.array([tRef-tRd/2, tRef+tRd/2])
        rxAmp = np.array([1,0])
        rxTime=np.concatenate((rxTimePrevious, rxTime),  axis=0)
        rxAmp=np.concatenate((rxAmpPrevious, rxAmp),  axis=0)
        return rxTime,  rxAmp
    
    # SAVE DATA
    def saveData(rawData):
        dt = datetime.now()
        dt_string = dt.strftime("%Y.%m.%d.%H.%M.%S")
        dt2 = date.today()
        dt2_string = dt2.strftime("%Y.%m.%d")
        if not os.path.exists('experiments/acquisitions/%s' % (dt2_string)):
            os.makedirs('experiments/acquisitions/%s' % (dt2_string))
                
        if not os.path.exists('experiments/acquisitions/%s/%s' % (dt2_string, dt_string)):
            os.makedirs('experiments/acquisitions/%s/%s' % (dt2_string, dt_string)) 
        rawData['fileName'] = "%s.%s.mat" % ("NOISE",dt_string)
        savemat("experiments/acquisitions/%s/%s/%s.%s.mat" % (dt2_string, dt_string, "NOISE_standalone",dt_string),  rawData) 
        
    
    #  STANDALONE FUNCTIONS
    def  plotData(data, tAdqReal, nRd):
       plt.figure(1)
       tPlot = np.linspace(0, tAdqReal, nReadout,  endpoint ='True')*1e-3
       plt.plot(tPlot[5:], np.abs(data[5:]))
       plt.plot(tPlot[5:], np.real(data[5:]))
       plt.plot(tPlot[5:], np.imag(data[5:]))
       plt.xlabel('t(ms)')
       plt.ylabel('A(mV)')
       vRMS=np.std(np.abs(data[5:]))
       titleRF= 'BW = '+ str(np.round(nRd/(tAdqReal)*1e3))+'kHz; Vrms ='+str(vRMS)
       plt.title(titleRF)
    
    
    def plotDataK(data, BW, nReadout):
            plt.figure(2)
            fAdq =  np.linspace(-BW/2, BW/2, nReadout, endpoint=True)*1e3
            dataFft = np.fft.fft(data[5:])
            dataOr1, dataOr2 = np.split(dataFft, 2, axis=0)
            dataFft= np.concatenate((dataOr2, dataOr1), axis=0)
            plt.plot(fAdq[5:], np.abs(dataFft), 'r-')
            plt.xlabel('f(kHz)')
            plt.ylabel('A(a.u.)')
            plt.title('FFT')
#            plt.xlim(-0.05,  0.05)
            plt.legend()


    # INIT EXPERIMENT
    BWov = BW*oversamplingFactor
    samplingPeriod = 1/BWov
    expt = ex.Experiment(lo_freq=larmorFreq, rx_t=samplingPeriod, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    samplingPeriod = expt.get_rx_ts()[0]
    BWReal = 1/samplingPeriod/oversamplingFactor
    tAdqReal = nReadout/BWReal  
    
    # SEQUENCE
    tStart = 20
    tRef = tStart+tAdqReal/2
    rxTime, rxAmp = readoutGate(tRef, tAdqReal, rxTime, rxAmp)
    expt.add_flodict({
                        'rx0_en': (rxTime, rxAmp),
                        'rx_gate': (rxTime, rxAmp),
                        })
    if plotSeq == 0:
        print('Running...')
        rxd, msgs = expt.run()
        expt.__del__()
        print('End')
        data = sig.decimate(rxd['rx0']*13.788, oversamplingFactor, ftype='fir', zero_phase=True)
        rawData['data'] = data
        saveData(rawData)
        plotData(data,tAdqReal, nReadout)
        plotDataK(data, BWReal, nReadout)
        plt.show()
    elif plotSeq == 1:
        expt.plot_sequence()
        plt.show()
        expt.__del__()
Пример #19
0
def grad_echo(self):

    ## All times are in the context of a single TR, starting at time 0
    tr_wait = 100
    trap_ramp_pts = 5
    phase_amps = np.linspace(self.phase_amp, -self.phase_amp, self.trs)

    #rf_tstart = 100 # us
    self.rf_tend = self.rf_tstart + self.rf_duration  # us

    slice_tstart = self.rf_tstart - self.trap_ramp_duration
    slice_duration = (
        self.rf_tend - self.rf_tstart
    ) + 2 * self.trap_ramp_duration  # includes rise, plateau and fall
    phase_tstart = self.rf_tend + self.phase_delay
    readout_tstart = phase_tstart
    readout_duration = self.phase_duration * 2

    rx_tstart = readout_tstart + self.trap_ramp_duration  # us
    rx_tend = readout_tstart + readout_duration - self.trap_ramp_duration  # us

    #    tx_gate_pre = 2 # us, time to start the TX gate before the RF pulse begins
    #    tx_gate_post = 1 # us, time to keep the TX gate on after the RF pulse ends

    tr_total_time = readout_tstart + readout_duration + tr_wait + 7000  # start-finish TR time

    def grad_echo_tr(tstart, pamp):
        gvxt, gvxa = trapezoid(self.slice_amp, slice_duration,
                               self.trap_ramp_duration, trap_ramp_pts)
        gvyt, gvya = trapezoid(pamp, self.phase_duration,
                               self.trap_ramp_duration, trap_ramp_pts)

        gvzt1 = trapezoid(self.readout_amp, readout_duration / 2,
                          self.trap_ramp_duration, trap_ramp_pts)
        gvzt2 = trapezoid(-self.readout_amp, readout_duration / 2,
                          self.trap_ramp_duration, trap_ramp_pts)
        gvzt = np.hstack([gvzt1[0], gvzt2[0] + readout_duration / 2])
        gvza = np.hstack([gvzt1[1], gvzt2[1]])

        rx_tcentre = (rx_tstart + rx_tend) / 2
        value_dict = {
            # second tx0 pulse purely for loopback debugging
            'tx0': (np.array([
                self.rf_tstart, self.rf_tend, rx_tcentre - 10, rx_tcentre + 10
            ]) + tstart,
                    np.array([self.rf_amp, 0, self.dbg_sc * (1 + 0.5j), 0])),
            'tx1': (np.array([rx_tstart + 15, rx_tend - 15]) + tstart,
                    np.array([self.dbg_sc * pamp * (1 + 0.5j), 0])),
            'grad_vx': (gvxt + tstart + slice_tstart, gvxa),
            'grad_vy': (gvyt + tstart + phase_tstart, gvya),
            'grad_vz': (gvzt + tstart + readout_tstart, gvza),
            'rx0_en':
            (np.array([rx_tstart, rx_tend]) + tstart, np.array([1, 0])),
            'rx1_en': (np.array([rx_tstart, rx_tend]) + tstart,
                       np.array([1, 0])),  # acquire on RX1 for example too
            'tx_gate': (np.array([
                self.rf_tstart - self.tx_gate_pre,
                self.rf_tend + self.tx_gate_post
            ]) + tstart, np.array([1, 0]))
        }

        return value_dict

    expt = ex.Experiment(lo_freq=self.lo_freq,
                         rx_t=self.rx_period,
                         init_gpa=self.init_gpa)

    tr_t = 20  # start the first TR at 20us
    for pamp in phase_amps:
        expt.add_flodict(grad_echo_tr(tr_t, pamp))
        tr_t += tr_total_time

    rxd, msgs = expt.run()
    expt.close_server(True)

    if self.plot_rx:

        return rxd['rx0'].real, rxd['rx0'].imag
Пример #20
0
def rabiflops_standalone(init_gpa=True,
                         larmorFreq=3.07232,
                         rfExAmp=0.0,
                         rfReAmp=None,
                         rfExPhase=0,
                         rfExTimeIni=0,
                         rfExTimeEnd=0,
                         nExTime=1,
                         nReadout=2501,
                         tAdq=50 * 1e3,
                         tEcho=300 * 1e3,
                         tRepetition=500 * 1e3,
                         plotSeq=0,
                         shimming=[0, 0, 0]):

    #BW 500 tAcq 5
    #BW 50   tAcq 50

    #  INITALISATION OF VARIABLES  ################################################################################
    #CONTANTS
    tStart = 20
    txGatePre = 15
    txGatePost = 1
    oversamplingFactor = 6
    shimming = np.array(shimming) * 1e-4

    #ARRAY INITIALIZATIONS
    txTime = []
    txAmp = []
    txGateTime = []
    txGateAmp = []
    rxTime = []
    rxAmp = []
    dataAll = []

    #RF PULSES
    if rfReAmp is None:
        rfReAmp = rfExAmp
    rfExPhase = rfExPhase * np.pi / 180
    rfExAmp = rfExAmp * np.exp(1j * rfExPhase)
    rfRePhase = 0
    rfReAmp = rfReAmp * np.exp(1j * rfRePhase)
    #Excitation times
    rfExTime = np.linspace(rfExTimeIni, rfExTimeEnd, nExTime, endpoint=True)

    #  DEFINITION OF PULSES   ####################################################################################
    def rfPulse(tRef, rfAmp, rfDuration, txTimePrevious, txAmpPrevious,
                txGateTimePrevious, txGateAmpPrevious):
        txTime = np.array([tRef - rfDuration / 2, tRef + rfDuration / 2])
        txAmp = np.array([rfAmp, 0.])
        txGateTime = np.array([txTime[0] - txGatePre, txTime[1] + txGatePost])
        txGateAmp = np.array([1, 0])
        txTime = np.concatenate((txTimePrevious, txTime), axis=0)
        txAmp = np.concatenate((txAmpPrevious, txAmp), axis=0)
        txGateTime = np.concatenate((txGateTimePrevious, txGateTime), axis=0)
        txGateAmp = np.concatenate((txGateAmpPrevious, txGateAmp), axis=0)
        return txTime, txAmp, txGateTime, txGateAmp

    def readoutGate(tRef, tRd, rxTimePrevious, rxAmpPrevious):
        rxTime = np.array([tRef - tRd / 2, tRef + tRd / 2])
        rxAmp = np.array([1, 0])
        rxTime = np.concatenate((rxTimePrevious, rxTime), axis=0)
        rxAmp = np.concatenate((rxAmpPrevious, rxAmp), axis=0)
        return rxTime, rxAmp

#  SPECIFIC FUNCTIONS   ####################################################################################

    def plotData(data, rfExTime, tAdqReal, nRd):
        plt.figure(1)
        for indexExTime in range(nExTime):
            tPlot = np.linspace(0, tAdqReal, nReadout, endpoint='True'
                                ) * 1e-3 + indexExTime * tAdqReal * 1e-3
            plt.plot(tPlot[5:], np.abs(data[indexExTime, 5:]))
            plt.plot(tPlot[5:], np.real(data[indexExTime, 5:]))
            plt.plot(tPlot[5:], np.imag(data[indexExTime, 5:]))
        plt.xlabel('t(ms)')
        plt.ylabel('A(mV)')
        vRMS = np.std(np.abs(data[0, 5:]))
        titleRF = 'BW = ' + str(np.round(
            nRd / (tAdqReal) * 1e3)) + 'kHz; Vrms =' + str(vRMS)
        plt.title(titleRF)

    def plotDataK(data, BW, nReadout):
        plt.figure(2)
        fAdq = np.linspace(-BW / 2, BW / 2, nReadout, endpoint=True) * 1e3
        dataFft = np.fft.fft(data[0, 5:])
        dataOr1, dataOr2 = np.split(dataFft, 2, axis=0)
        dataFft = np.concatenate((dataOr2, dataOr1), axis=0)
        plt.plot(fAdq[5:], np.abs(dataFft), 'r-')
        plt.xlabel('f(kHz)')
        plt.ylabel('A(a.u.)')
        plt.title('FFT')
        #            plt.xlim(-0.05,  0.05)
        plt.legend()

#  SEQUENCE  ############################################################################################

    for indexExTime in range(nExTime):

        rfReTime = 2 * rfExTime[indexExTime]

        txTime = []
        txAmp = []
        txGateTime = []
        txGateAmp = []
        rxTime = []
        rxAmp = []

        # INIT EXPERIMENT
        BW = nReadout / tAdq
        BWov = BW * oversamplingFactor
        samplingPeriod = 1 / BWov
        expt = ex.Experiment(lo_freq=larmorFreq,
                             rx_t=samplingPeriod,
                             init_gpa=init_gpa,
                             gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
        samplingPeriod = expt.get_rx_ts()[0]
        BWReal = 1 / samplingPeriod / oversamplingFactor
        tAdqReal = nReadout / BWReal
        # TR
        tRef = tStart + rfExTime[indexExTime] / 2
        txTime, txAmp, txGateTime, txGateAmp = rfPulse(tRef, rfExAmp,
                                                       rfExTime[indexExTime],
                                                       txTime, txAmp,
                                                       txGateTime, txGateAmp)
        tRef = tRef + tEcho / 2
        txTime, txAmp, txGateTime, txGateAmp = rfPulse(tRef, rfReAmp, rfReTime,
                                                       txTime, txAmp,
                                                       txGateTime, txGateAmp)
        tRef = tRef + tEcho / 2
        rxTime, rxAmp = readoutGate(tRef, tAdqReal, rxTime, rxAmp)

        expt.add_flodict({
            'tx0': (txTime, txAmp),
            'tx_gate': (txGateTime, txGateAmp),
            'rx0_en': (rxTime, rxAmp),
            'rx_gate': (rxTime, rxAmp),
        })
        if plotSeq == 0:
            print(indexExTime, '.- Running...')
            rxd, msgs = expt.run()
            expt.__del__()
            print('   End')
            data = sig.decimate(rxd['rx0'] * 13.788,
                                oversamplingFactor,
                                ftype='fir',
                                zero_phase=True)
            dataAll = np.concatenate((dataAll, data), axis=0)
        elif plotSeq == 1:
            expt.plot_sequence()
            plt.show()
            expt.__del__()

    if plotSeq == 1:
        expt.plot_sequence()
        plt.show()
        expt.__del__()
    elif plotSeq == 0:
        data = np.reshape(dataAll, (nExTime, nReadout))
        plotData(data, rfExTime, tAdqReal, nReadout)
        plotDataK(data, BWReal, nReadout)
        plt.show()
def inversionrecoveryStandalone(
        init_gpa=False,
        lo_freq=3.074,
        rf_amp=0.3,
        rf_pi_duration=None,
        rf_pi2_duration=33,
        tr=5,  # s
        t_ini=10e-4,  # s
        t_fin=3,  # s
        N=20,
        shimming=[-80, -100, 10]):

    BW = 60 * 1e-3  # MHz
    n_rd = 120
    plotSeq = 0
    point = 8
    blk_delay = 300
    shimming = np.array(shimming) * 1e-4

    if rf_pi_duration is None:
        rf_pi_duration = 2 * rf_pi2_duration

    rawData = {}
    rawData['larmorFreq'] = lo_freq * 1e6
    rawData['rfAmp'] = rf_amp
    rawData['rfInTime'] = rf_pi_duration
    rawData['rfExtime'] = rf_pi2_duration
    rawData['TR'] = tr * 1e-6
    rawData['tInvIni'] = t_ini * 1e-6
    rawData['tInvFin'] = t_fin * 1e-6
    rawData['nRepetitions'] = N
    rawData['bw'] = BW * 1e6
    rawData['nRD'] = n_rd
    rawData['point'] = point

    t_adq = n_rd / BW

    tx_gate_pre = 15  # us, time to start the TX gate before each RF pulse begins
    tx_gate_post = 1  # us, time to keep the TX gate on after an RF pulse ends

    rx_period = 1 / BW

    expt = ex.Experiment(lo_freq=lo_freq,
                         rx_t=rx_period,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))

    # Create functions
    def endSequence(tEnd):
        expt.add_flodict({
            'grad_vx': (np.array([tEnd]), np.array([0])),
            'grad_vy': (np.array([tEnd]), np.array([0])),
            'grad_vz': (np.array([tEnd]), np.array([0])),
        })

    def iniSequence(tEnd, shimming):
        expt.add_flodict({
            'grad_vx': (np.array([tEnd]), np.array([shimming[0]])),
            'grad_vy': (np.array([tEnd]), np.array([shimming[1]])),
            'grad_vz': (np.array([tEnd]), np.array([shimming[2]])),
        })

    tIni = 20
    t = t_ini * 1e6
    tIR = np.geomspace(t_ini, t_fin,
                       N) * 1e6  # in us to be used in the sequence
    tr = tr * 1e6

    # Shimming
    iniSequence(tIni, shimming)
    t_start = 2 * tIni

    for t in tIR:

        tx_t = np.array([
            t_start, t_start + rf_pi_duration,
            t_start + t + rf_pi2_duration / 2,
            t_start + t + 3 * rf_pi2_duration / 2
        ])
        tx_a = np.array([1j * rf_amp, 0, rf_amp, 0])

        tx_gate_t = np.array([
            t_start - tx_gate_pre, t_start + rf_pi_duration + tx_gate_post,
            t_start + t + rf_pi2_duration / 2 - tx_gate_pre,
            t_start + t + 3 * rf_pi2_duration / 2 + tx_gate_post
        ])
        tx_gate_a = np.array([1, 0, 1, 0])

        readout_t = np.array([
            t_start, t_start + t + 3 * rf_pi2_duration / 2 + blk_delay,
            t_start + t + 3 * rf_pi2_duration / 2 + t_adq + blk_delay
        ])
        readout_a = np.array([0, 1, 0])

        rx_gate_t = readout_t
        rx_gate_a = readout_a

        expt.add_flodict({
            'tx0': (tx_t, tx_a),
            'tx_gate': (tx_gate_t, tx_gate_a),
            'rx0_en': (readout_t, readout_a),
            'rx_gate': (rx_gate_t, rx_gate_a),
        })

        t_start += tr

    tFin = t_start
    endSequence(tFin)

    # Representar Secuencia o tomar los datos.
    tIR1 = np.geomspace(t_ini, t_fin, N)
    tIR2 = np.geomspace(t_ini, t_fin, 10 * N)
    if plotSeq == 1:
        expt.plot_sequence()
        plt.show()
        expt.__del__()
    elif plotSeq == 0:
        print('Running...')
        rxd, msgs = expt.run()
        print('End')
        data = rxd['rx0'] * 13.788
        expt.__del__()
        rawData['fullData'] = data
        dataIndiv = np.reshape(data, (N, n_rd))
        dataIndiv = np.real(dataIndiv[:, point] *
                            np.exp(-1j * (np.angle(dataIndiv[0, 1]) + np.pi)))
        results = np.transpose(np.array([tIR1, dataIndiv / np.max(dataIndiv)]))
        rawData['signalVsTime'] = results

        # For 1 component
        fitData1, xxx = curve_fit(func1, results[:, 0], results[:, 1])
        print('For one component:')
        print('mA', round(fitData1[0], 1))
        print('T1', round(fitData1[1] * 1e3), ' ms')
        rawData['T11'] = fitData1[1] * 1e3
        rawData['M1'] = fitData1[0]

        # For 2 components
        fitData2, xxx = curve_fit(func2,
                                  results[:, 0],
                                  results[:, 1],
                                  p0=(1, 0.1, 0.5, 0.05),
                                  bounds=(0., 5.))
        print('For two components:')
        print('Ma', round(fitData2[0], 1))
        print('Mb', round(fitData2[2], 1))
        print('T1a', round(fitData2[1] * 1e3), ' ms')
        print('T1b', round(fitData2[3] * 1e3), ' ms')
        rawData['T12'] = [fitData2[1], fitData2[3]]
        rawData['M2'] = [fitData2[0], fitData2[2]]

        # For 3 components
        fitData3, xxx = curve_fit(func3,
                                  results[:, 0],
                                  results[:, 1],
                                  p0=(1, 0.1, 0.5, 0.05, 1, 0.01),
                                  bounds=(0., 5.))
        print('For three components:')
        print('Ma', round(fitData3[0], 1), ' ms')
        print('Mb', round(fitData3[2], 1), ' ms')
        print('Mc', round(fitData3[4], 1), ' ms')
        print('T1a', round(fitData3[1] * 1e3), ' ms')
        print('T1b', round(fitData3[3] * 1e3), ' ms')
        print('T1c', round(fitData3[5] * 1e3), ' ms')
        rawData['T13'] = [fitData3[1], fitData3[3], fitData3[5]]
        rawData['M3'] = [fitData3[0], fitData3[2], fitData3[4]]

        # Save data
        name = saveMyData(rawData)

        # Plots
        plt.figure(2, figsize=(5, 5))
        plt.plot(results[:, 0], results[:, 1], 'o')
        plt.plot(tIR2, func1(tIR2, *fitData1))
        plt.plot(tIR2, func2(tIR2, *fitData2))
        plt.plot(tIR2, func3(tIR2, *fitData3))
        plt.title(name)
        plt.xscale('log')
        plt.xlabel('t(ms)')
        plt.ylabel('Signal (mV)')
        plt.legend([
            'Experimental', 'Fitting 1 component', 'Fitting 2 components',
            'Fitting 3 components'
        ])
        plt.title(name)
        plt.show()
Пример #22
0
def tse_batches(
    init_gpa=False,  # Starts the gpa
    nScans=1,  # NEX
    larmorFreq=3.07564e6,  # Larmor frequency
    rfExAmp=0.3,  # rf excitation pulse amplitude
    rfReAmp=0.3,  # rf refocusing pulse amplitude
    rfExTime=35e-6,  # rf excitation pulse time
    rfReTime=70e-6,  # rf refocusing pulse time
    echoSpacing=20e-3,  # time between echoes
    inversionTime=0,  # Inversion recovery time
    repetitionTime=500e-3,  # TR
    fov=np.array([12e-2, 12e-2, 12e-2]),  # FOV along readout, phase and slice
    dfov=np.array([0e-2, 0e-2, 0e-2]),  # Displacement of fov center
    nPoints=np.array([60, 60,
                      30]),  # Number of points along readout, phase and slice
    etl=30,  # Echo train length
    acqTime=2e-3,  # Acquisition time
    axes=np.array([0, 2, 1]),  # 0->x, 1->y and 2->z defined as [rd,ph,sl]
    axesEnable=np.array([1, 0, 0]),  # 1-> Enable, 0-> Disable
    sweepMode=1,  # 0->k2k (T2),  1->02k (T1),  2->k20 (T2), 3->Niquist modulated (T2)
    phaseGradTime=1000e-6,  # Phase and slice dephasing time
    rdPreemphasis=1.025,
    drfPhase=0,  # phase of the excitation pulse (in degrees)
    dummyPulses=1,  # Dummy pulses for T1 stabilization
    shimming=np.array([-70, -90,
                       10]),  # Shimming along the X,Y and Z axes (a.u. *1e4)
    parAcqLines=0  # Number of additional lines, Full sweep if 0
):

    print('Start sequence')

    # rawData fields
    rawData = {}
    inputs = {}
    outputs = {}
    auxiliar = {}

    # Inputs for rawData
    inputs['nScans'] = nScans
    inputs['larmorFreq'] = larmorFreq  # Larmor frequency
    inputs['rfExAmp'] = rfExAmp  # rf excitation pulse amplitude
    inputs['rfReAmp'] = rfReAmp  # rf refocusing pulse amplitude
    inputs['rfExTime'] = rfExTime  # rf excitation pulse time
    inputs['rfReTime'] = rfReTime  # rf refocusing pulse time
    inputs['echoSpacing'] = echoSpacing  # time between echoes
    inputs['inversionTime'] = inversionTime  # Inversion recovery time
    inputs['repetitionTime'] = repetitionTime  # TR
    inputs['fov'] = np.array(fov) * 1e-3  # FOV along readout, phase and slice
    inputs['dfov'] = dfov  # Displacement of fov center
    inputs[
        'nPoints'] = nPoints  # Number of points along readout, phase and slice
    inputs['etl'] = etl  # Echo train length
    inputs['acqTime'] = acqTime  # Acquisition time
    inputs['axes'] = axes  # 0->x, 1->y and 2->z defined as [rd,ph,sl]
    inputs['axesEnable'] = axesEnable  # 1-> Enable, 0-> Disable
    inputs[
        'sweepMode'] = sweepMode  # 0->k2k (T2),  1->02k (T1),  2->k20 (T2), 3->Niquist modulated (T2)
    inputs['phaseGradTime'] = phaseGradTime  # Phase and slice dephasing time
    inputs['rdPreemphasis'] = rdPreemphasis
    inputs['drfPhase'] = drfPhase
    inputs['dummyPulses'] = dummyPulses  # Dummy pulses for T1 stabilization
    inputs['partialAcquisition'] = parAcqLines

    # Conversion of variables to non-multiplied units
    larmorFreq = larmorFreq * 1e6
    rfExTime = rfExTime * 1e-6
    rfReTime = rfReTime * 1e-6
    fov = np.array(fov) * 1e-3
    dfov = np.array(dfov) * 1e-3
    echoSpacing = echoSpacing * 1e-3
    acqTime = acqTime * 1e-3
    shimming = np.array(shimming) * 1e-4
    repetitionTime = repetitionTime * 1e-3
    inversionTime = inversionTime * 1e-3
    phaseGradTime = phaseGradTime * 1e-6

    init_gpa = False  # Starts the gpa

    # Miscellaneous
    blkTime = 10  # Deblanking time (us)
    larmorFreq = larmorFreq * 1e-6
    gradRiseTime = 400e-6  # Estimated gradient rise time
    gSteps = int(gradRiseTime * 1e6 / 5)
    gradDelay = 9  # Gradient amplifier delay
    addRdPoints = 10  # Initial rd points to avoid artifact at the begining of rd
    gammaB = 42.56e6  # Gyromagnetic ratio in Hz/T
    deadTime = 200
    oversamplingFactor = 6
    addRdGradTime = 1000  # Additional readout gradient time to avoid turn on/off effects on the Rx channel
    randFactor = 0e-3  # Random amplitude to add to the phase gradients
    if rfReAmp == 0:
        rfReAmp = rfExAmp
    if rfReTime == 0:
        rfReTime = 2 * rfExTime

    auxiliar['gradDelay'] = gradDelay * 1e-6
    auxiliar['gradRiseTime'] = gradRiseTime
    auxiliar['oversamplingFactor'] = oversamplingFactor
    auxiliar['addRdGradTime'] = addRdGradTime * 1e-6
    auxiliar['randFactor'] = randFactor
    auxiliar['addRdPoints'] = addRdPoints

    # Matrix size
    nRD = nPoints[0] + 2 * addRdPoints
    nPH = nPoints[1] * axesEnable[1] + (1 - axesEnable[1])
    nSL = nPoints[2] * axesEnable[2] + (1 - axesEnable[2])

    # ETL if nPH = 1
    if etl > nPH:
        etl = nPH

    # parAcqLines in case parAcqLines = 0
    if parAcqLines == 0:
        parAcqLines = np.int(nSL / 2)

    # BW
    BW = nPoints[0] / acqTime * 1e-6
    BWov = BW * oversamplingFactor
    samplingPeriod = 1 / BWov

    # Readout dephasing time
    rdDephTime = (acqTime - gradRiseTime) / 2

    # Phase and slice de- and re-phasing time
    if phaseGradTime == 0:
        phaseGradTime = echoSpacing / 2 - rfExTime / 2 - rfReTime / 2 - 2 * gradRiseTime
    elif phaseGradTime > echoSpacing / 2 - rfExTime / 2 - rfReTime / 2 - 2 * gradRiseTime:
        phaseGradTime = echoSpacing / 2 - rfExTime / 2 - rfReTime / 2 - 2 * gradRiseTime

    # Max gradient amplitude
    rdGradAmplitude = nPoints[0] / (gammaB * fov[0] * acqTime) * axesEnable[0]
    phGradAmplitude = nPH / (2 * gammaB * fov[1] *
                             (phaseGradTime + gradRiseTime)) * axesEnable[1]
    slGradAmplitude = nSL / (2 * gammaB * fov[2] *
                             (phaseGradTime + gradRiseTime)) * axesEnable[2]
    auxiliar['rdGradAmplitude'] = rdGradAmplitude
    auxiliar['phGradAmplitude'] = phGradAmplitude
    auxiliar['slGradAmplitude'] = slGradAmplitude

    # Change gradient values to OCRA units
    gFactor = reorganizeGfactor(axes)
    auxiliar['gFactor'] = gFactor
    rdGradAmplitude = rdGradAmplitude / gFactor[0] * 1000 / 5
    phGradAmplitude = phGradAmplitude
    slGradAmplitude = slGradAmplitude

    # Phase and slice gradient vector
    phGradients = np.linspace(-phGradAmplitude,
                              phGradAmplitude,
                              num=nPH,
                              endpoint=False)
    slGradients = np.linspace(-slGradAmplitude,
                              slGradAmplitude,
                              num=nSL,
                              endpoint=False)

    # Now fix the number of slices to partailly acquired k-space
    nSL = (np.int(nPoints[2] / 2) + parAcqLines) * axesEnable[2] + (
        1 - axesEnable[2])

    # Add random displacemnt to phase encoding lines
    for ii in range(nPH):
        if ii < np.ceil(nPH / 2 - nPH / 20) or ii > np.ceil(nPH / 2 +
                                                            nPH / 20):
            phGradients[ii] = phGradients[ii] + randFactor * np.random.randn()
    auxiliar['phGradients'] = phGradients
    auxiliar['slGradients'] = slGradients
    kPH = gammaB * phGradients * (gradRiseTime + phaseGradTime)
    phGradients = phGradients / gFactor[1] * 1000 / 5
    slGradients = slGradients / gFactor[2] * 1000 / 5

    # Set phase vector to given sweep mode
    ind = getIndex(phGradients, etl, nPH, sweepMode)
    phGradients = phGradients[::-1]
    phGradients = phGradients[ind]

    def rfPulse(tStart, rfTime, rfAmplitude, rfPhase):
        txTime = np.array([tStart + blkTime, tStart + blkTime + rfTime])
        txAmp = np.array([rfAmplitude * np.exp(1j * rfPhase), 0.])
        txGateTime = np.array([tStart, tStart + blkTime + rfTime])
        txGateAmp = np.array([1, 0])
        expt.add_flodict({
            'tx0': (txTime, txAmp),
            'tx_gate': (txGateTime, txGateAmp)
        })

    def rxGate(tStart, gateTime):
        rxGateTime = np.array([tStart, tStart + gateTime])
        rxGateAmp = np.array([1, 0])
        expt.add_flodict({
            'rx0_en': (rxGateTime, rxGateAmp),
            'rx_gate': (rxGateTime, rxGateAmp),
        })

    def gradTrap(tStart, gTime, gAmp, gAxis):
        tUp = np.linspace(tStart,
                          tStart + gradRiseTime,
                          num=gSteps,
                          endpoint=False)
        tDown = tUp + gradRiseTime + gTime
        t = np.concatenate((tUp, tDown), axis=0)
        dAmp = gAmp / gSteps
        aUp = np.linspace(dAmp, gAmp, num=gSteps)
        aDown = np.linspace(gAmp - dAmp, 0, num=gSteps)
        a = np.concatenate((aUp, aDown), axis=0)
        if gAxis == 0:
            expt.add_flodict({'grad_vx': (t, a + shimming[0])})
        elif gAxis == 1:
            expt.add_flodict({'grad_vy': (t, a + shimming[1])})
        elif gAxis == 2:
            expt.add_flodict({'grad_vz': (t, a + shimming[2])})

    def gradPulse(tStart, gTime, gAmp, gAxes):
        t = np.array([tStart, tStart + gradRiseTime + gTime])
        for gIndex in range(np.size(gAxes)):
            a = np.array([gAmp[gIndex], 0])
            if gAxes[gIndex] == 0:
                expt.add_flodict({'grad_vx': (t, a + shimming[0])})
            elif gAxes[gIndex] == 1:
                expt.add_flodict({'grad_vy': (t, a + shimming[1])})
            elif gAxes[gIndex] == 2:
                expt.add_flodict({'grad_vz': (t, a + shimming[2])})

    def endSequence(tEnd):
        expt.add_flodict({
            'grad_vx': (np.array([tEnd]), np.array([0])),
            'grad_vy': (np.array([tEnd]), np.array([0])),
            'grad_vz': (np.array([tEnd]), np.array([0])),
        })

    def iniSequence(tEnd):
        expt.add_flodict({
            'grad_vx': (np.array([tEnd]), np.array([shimming[0]])),
            'grad_vy': (np.array([tEnd]), np.array([shimming[1]])),
            'grad_vz': (np.array([tEnd]), np.array([shimming[2]])),
        })

    def createSequence():
        phIndex = 0
        slIndex = 0
        scanTime = (nPH * nSL / etl + dummyPulses) * repetitionTime
        # Set shimming
        iniSequence(20)
        for repeIndex in range(int(nPH * nSL / etl) + dummyPulses):
            # Initialize time
            t0 = 20 + repetitionTime * repeIndex

            # Inversion pulse
            if inversionTime != 0:
                rfPulse(t0, rfReTime, rfReAmp, 0)

            # Excitation pulse
            t0 += rfReTime / 2 + inversionTime - rfExTime / 2
            rfPulse(t0, rfExTime, rfExAmp, drfPhase * np.pi / 180)

            # Dephasing readout
            t0 += blkTime + rfExTime - gradDelay
            if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                gradTrap(t0, acqTime + 2 * addRdGradTime,
                         rdGradAmplitude / 2 * rdPreemphasis, axes[0])

            # First readout to avoid RP initial readout effect

    #        if repeIndex==0:         # This is to account for dummy pulses
    #            rxGate(t0+gradDelay+deadTime, acqTime+2*addRdPoints/BW)

    # Echo train
            for echoIndex in range(etl):
                # Refocusing pulse
                if echoIndex == 0:
                    t0 += (-rfExTime + echoSpacing - rfReTime) / 2 - blkTime
                else:
                    t0 += gradDelay - acqTime / 2 + echoSpacing / 2 - rfReTime / 2 - blkTime - addRdGradTime
                rfPulse(t0, rfReTime, rfReAmp, np.pi / 2)

                # Dephasing phase and slice gradients
                t0 += blkTime + rfReTime
                if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                    gradTrap(t0, phaseGradTime, phGradients[phIndex], axes[1])
                    gradTrap(t0, phaseGradTime, slGradients[slIndex], axes[2])

                # Readout gradient
                t0 += -rfReTime / 2 + echoSpacing / 2 - acqTime / 2 - gradRiseTime - gradDelay - addRdGradTime
                if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                    gradTrap(t0, acqTime + 2 * addRdGradTime, rdGradAmplitude,
                             axes[0])

                # Rx gate
                t0 += gradDelay + gradRiseTime + addRdGradTime - addRdPoints / BW
                if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                    rxGate(t0, acqTime + 2 * addRdPoints / BW)

                # Rephasing phase and slice gradients
                t0 += addRdPoints / BW + acqTime - gradDelay + addRdGradTime
                if (echoIndex < etl - 1 and repeIndex >= dummyPulses):
                    gradTrap(t0, phaseGradTime, -phGradients[phIndex], axes[1])
                    gradTrap(t0, phaseGradTime, -slGradients[slIndex], axes[2])

                # Update the phase and slice gradient
                if repeIndex >= dummyPulses:
                    if phIndex == nPH - 1:
                        phIndex = 0
                        slIndex += 1
                    else:
                        phIndex += 1

                if phIndex == nPH - 1 and slIndex == nSL - 1:
                    endSequence(scanTime)

    def createFreqCalSequence():
        t0 = 20

        # Shimming
        iniSequence(t0)

        # Excitation pulse
        rfPulse(t0, rfExTime, rfExAmp, drfPhase * np.pi / 180)

        # Refocusing pulse
        t0 += rfExTime / 2 + echoSpacing / 2 - rfReTime / 2
        rfPulse(t0, rfReTime, rfReAmp, np.pi / 2)

        # Rx
        t0 += blkTime + rfReTime / 2 + echoSpacing / 2 - acqTime / 2 - addRdPoints / BW
        rxGate(t0, acqTime + 2 * addRdPoints / BW)

        # Finalize sequence
        endSequence(repetitionTime)

    # Changing time parameters to us
    rfExTime = rfExTime * 1e6
    rfReTime = rfReTime * 1e6
    echoSpacing = echoSpacing * 1e6
    repetitionTime = repetitionTime * 1e6
    gradRiseTime = gradRiseTime * 1e6
    phaseGradTime = phaseGradTime * 1e6
    rdDephTime = rdDephTime * 1e6
    inversionTime = inversionTime * 1e6

    # Calibrate frequency
    expt = ex.Experiment(lo_freq=larmorFreq,
                         rx_t=samplingPeriod,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    samplingPeriod = expt.get_rx_ts()[0]
    BW = 1 / samplingPeriod / oversamplingFactor
    acqTime = nPoints[0] / BW  # us
    auxiliar['bandwidth'] = BW * 1e6
    createFreqCalSequence()
    rxd, msgs = expt.run()
    dataFreqCal = sig.decimate(rxd['rx0'] * 13.788,
                               oversamplingFactor,
                               ftype='fir',
                               zero_phase=True)
    dataFreqCal = dataFreqCal[addRdPoints:nPoints[0] + addRdPoints]
    # Plot fid
    plt.figure(1)
    tVector = np.linspace(
        -acqTime / 2, acqTime / 2, num=nPoints[0], endpoint=True) * 1e-3
    for ii in range(nPH):
        plt.subplot(1, 2, 1)
        plt.plot(tVector, np.abs(dataFreqCal))
        plt.title("Signal amplitude")
        plt.xlabel("Time (ms)")
        plt.ylabel("Amplitude (mV)")
        plt.subplot(1, 2, 2)
        angle = np.unwrap(np.angle(dataFreqCal))
        plt.title("Signal phase")
        plt.xlabel("Time (ms)")
        plt.ylabel("Phase (rad)")
        plt.plot(tVector, angle)
    # Get larmor frequency
    dPhi = angle[-1] - angle[0]
    df = dPhi / (2 * np.pi * acqTime)
    larmorFreq += df
    auxiliar['larmorFreq'] = larmorFreq * 1e6
    print("f0 = %s MHz" % (round(larmorFreq, 5)))
    # Delete experiment:
    expt.__del__()

    # Create full sequence
    expt = ex.Experiment(lo_freq=larmorFreq,
                         rx_t=samplingPeriod,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    samplingPeriod = expt.get_rx_ts()[0]
    BW = 1 / samplingPeriod / oversamplingFactor
    acqTime = nPoints[0] / BW  # us
    createSequence()

    if plotSeq == 1:  # Plot sequence
        expt.plot_sequence()
        plt.show()
        expt.__del__()
    elif plotSeq == 0:  # Run experiment
        dataFull = []
        for ii in range(nScans):
            rxd, msgs = expt.run()
            rxd['rx0'] = rxd[
                'rx0'] * 13.788  # Here I normalize to get the result in mV
            # Get data
            scanData = sig.decimate(rxd['rx0'],
                                    oversamplingFactor,
                                    ftype='fir',
                                    zero_phase=True)
            #scanData = rxd['rx0']
            #dataFull = np.concatenate((dataFull, scanData[nRD:]), axis = 0)
            dataFull = np.concatenate((dataFull, scanData), axis=0)
        expt.__del__()

        # Get index for krd = 0
        # Average data
        dataProv = np.reshape(dataFull, (nScans, nRD * nPH * nSL))
        dataProv = np.average(dataProv, axis=0)
        dataProv = np.reshape(dataProv, (nSL, nPH, nRD))
        # Reorganize the data acording to sweep mode
        dataTemp = dataProv * 0
        for ii in range(nPH):
            dataTemp[:, ind[ii], :] = dataProv[:, ii, :]
        dataProv = dataTemp
        # Check where is krd = 0
        dataProv = dataProv[int(nSL / 2), int(nPH / 2), :]
        indkrd0 = np.argmax(np.abs(dataProv))

        # Get required readout points
        dataFull = np.reshape(dataFull, (nPH * nSL * nScans, nRD))
        dataFull = dataFull[:, indkrd0 - int(nPoints[0] / 2):indkrd0 +
                            int(nPoints[0] / 2)]
        dataFull = np.reshape(dataFull, (1, nPoints[0] * nPH * nSL * nScans))

        # Average data
        data = np.reshape(dataFull, (nScans, nPoints[0] * nPH * nSL))
        data = np.average(data, axis=0)
        data = np.reshape(data, (nSL, nPH, nPoints[0]))

        # Reorganize the data acording to sweep mode
        dataTemp = data * 0
        for ii in range(nPH):
            dataTemp[:, ind[ii], :] = data[:, ii, :]

        # Do zero padding
        data = np.zeros((nPoints[2], nPoints[1], nPoints[0]))
        data = data + 1j * data
        if nSL == 1:
            data = dataTemp
        else:
            data[0:nSL - 1, :, :] = dataTemp[0:nSL - 1, :, :]
        data = np.reshape(data, (1, nPoints[0] * nPoints[1] * nPoints[2]))

        # Fix the position of the sample according t dfov
        kMax = np.array(nPoints) / (2 * np.array(fov)) * np.array(axesEnable)
        kRD = np.linspace(-kMax[0], kMax[0], num=nPoints[0], endpoint=False)
        #        kPH = np.linspace(-kMax[1],kMax[1],num=nPoints[1],endpoint=False)
        kSL = np.linspace(-kMax[2], kMax[2], num=nPoints[2], endpoint=False)
        kPH = kPH[::-1]
        kPH, kSL, kRD = np.meshgrid(kPH, kSL, kRD)
        kRD = np.reshape(kRD, (1, nPoints[0] * nPoints[1] * nPoints[2]))
        kPH = np.reshape(kPH, (1, nPoints[0] * nPoints[1] * nPoints[2]))
        kSL = np.reshape(kSL, (1, nPoints[0] * nPoints[1] * nPoints[2]))
        dPhase = np.exp(-2 * np.pi * 1j *
                        (dfov[0] * kRD + dfov[1] * kPH + dfov[2] * kSL))
        data = np.reshape(data * dPhase, (nPoints[2], nPoints[1], nPoints[0]))
        data = np.reshape(data, (1, nPoints[0] * nPoints[1] * nPoints[2]))

        # Create sampled data
        kRD = np.reshape(kRD, (nPoints[0] * nPoints[1] * nPoints[2], 1))
        kPH = np.reshape(kPH, (nPoints[0] * nPoints[1] * nPoints[2], 1))
        kSL = np.reshape(kSL, (nPoints[0] * nPoints[1] * nPoints[2], 1))
        data = np.reshape(data, (nPoints[0] * nPoints[1] * nPoints[2], 1))
        auxiliar['kMax'] = kMax
        outputs['sampled'] = np.concatenate((kRD, kPH, kSL, data), axis=1)

        # Reshape to 0 dimensional
        data = np.reshape(data, -1)

        # Save data
        dt = datetime.now()
        dt_string = dt.strftime("%Y.%m.%d.%H.%M.%S")
        dt2 = date.today()
        dt2_string = dt2.strftime("%Y.%m.%d")
        if not os.path.exists('experiments/acquisitions/%s' % (dt2_string)):
            os.makedirs('experiments/acquisitions/%s' % (dt2_string))

        if not os.path.exists('experiments/acquisitions/%s/%s' %
                              (dt2_string, dt_string)):
            os.makedirs('experiments/acquisitions/%s/%s' %
                        (dt2_string, dt_string))
        auxiliar['fileName'] = "%s.%s.mat" % ("RARE", dt_string)
        rawData['inputs'] = inputs
        rawData['auxiliar'] = auxiliar
        rawData['kSpace'] = outputs
        rawdata = {}
        rawdata['rawData'] = rawData
        savemat(
            "experiments/acquisitions/%s/%s/%s.%s.mat" %
            (dt2_string, dt_string, "Old_RARE", dt_string), rawdata)

        print('End sequence')
        return dataFull, msgs, data, BW
Пример #23
0
def propellerStack_standalone(
    init_gpa=False,  # Starts the gpa
    nScans=1,  # NEX
    larmorFreq=3.0746e6,  # Larmor frequency
    rfExAmp=0.3,  # rf excitation pulse amplitude
    rfReAmp=0.3,  # rf refocusing pulse amplitude
    rfExTime=40e-6,  # rf excitation pulse time
    rfReTime=80e-6,  # rf refocusing pulse time
    echoSpacing=20e-3,  # time between echoes
    repetitionTime=200e-3,  # TR
    inversionTime=0e-3,  # Inversion time for Inversino Recovery experiment
    fov=np.array([6.5e-2, 6.5e-2,
                  13e-2]),  # FOV along readout, phase and slice
    dfov=np.array([0e-2, 0e-2, 0e-2]),  # Displacement of fov center
    nPoints=np.array([60, 60,
                      30]),  # Number of points along readout, phase and slice
    etl=5,  # Echo train length
    undersampling=1,  # Angular undersampling
    acqTimeMax=2e-3,  # Maximum acquisition time (s)
    axes=np.array([2, 1, 0]),  # 0->x, 1->y and 2->z defined as [rd,ph,sl]
    sweepMode=1,  # 0->k2k (T2),  1->02k (T1),  2->k20 (T2), 3->Niquist modulated (T2)
    phaseGradTime=1000e-6,  # Phase and slice dephasing time
    rdPreemphasis=1.012,  # Readout preemphasis factor (dephasing gradient is multiplied by this number)
    drfPhase=0,  # phase of the excitation pulse (in degrees)
    dummyPulses=3,  # Dummy pulses for T1 stabilization
    shimming=np.array([-80, -100,
                       20]),  # Shimming along the X,Y and Z axes (a.u. *1e4)
    parAcqLines=0,  # Number of additional lines, Full sweep if 0
    phi0=45  # Rotates the rd/ph 
):

    # Test for linearly dependent preemphasis
    rdP0 = 1.00  # premphasis for G = 0
    rdPm = 10.5e-2  # Additional preemphasis per each unit voltage

    # rawData fields
    rawData = {}
    inputs = {}
    kSpace = {}
    auxiliar = {}

    # Miscellaneous
    blkTime = 10  # Deblanking time (us)
    larmorFreq = larmorFreq * 1e-6
    gradRiseTime = 400e-6  # Estimated gradient rise time
    gSteps = int(gradRiseTime * 1e6 / 10) * 0 + 1  # Gradient ramp steps
    gradDelay = 9  # Gradient amplifier delay
    addRdPoints = 10  # Initial rd points to avoid artifact at the begining of rd
    addRdGradTime = 1000  # Additional readout gradient time to avoid turn on/off effects on the Rx channel
    gammaB = 42.56e6  # Gyromagnetic ratio in Hz/T
    rfReAmp = rfExAmp
    rfReTime = 2 * rfExTime
    shimming = shimming * 1e-4
    resolution = fov / nPoints
    kMax = 1 / (2 * resolution)
    oversamplingFactor = 6
    auxiliar['resolution'] = resolution
    auxiliar['kMax'] = kMax
    auxiliar['gradDelay'] = gradDelay * 1e-6
    auxiliar['gradRiseTime'] = gradRiseTime
    auxiliar['oversamplingFactor'] = oversamplingFactor
    auxiliar['addRdGradTime'] = addRdGradTime * 1e-6

    # Inputs for rawData
    inputs['nScans'] = nScans
    inputs['larmorFreq'] = larmorFreq  # Larmor frequency
    inputs['rfExAmp'] = rfExAmp  # rf excitation pulse amplitude
    inputs['rfReAmp'] = rfReAmp  # rf refocusing pulse amplitude
    inputs['rfExTime'] = rfExTime  # rf excitation pulse time
    inputs['rfReTime'] = rfReTime  # rf refocusing pulse time
    inputs['echoSpacing'] = echoSpacing  # time between echoes
    inputs['repetitionTime'] = repetitionTime  # TR
    inputs[
        'inversionTime'] = inversionTime  # Inversion time for Inversion Recovery
    inputs['fov'] = fov  # FOV along readout, phase and slice
    inputs['dfov'] = dfov  # Displacement of fov center
    inputs[
        'nPoints'] = nPoints  # Number of points along readout, phase and slice
    inputs['etl'] = etl  # Echo train length
    inputs['undersampling'] = undersampling  # Angular undersampling
    inputs['acqTimeMax'] = acqTimeMax  # Acquisition bandwidth
    inputs['axes'] = axes  # 0->x, 1->y and 2->z defined as [rd,ph,sl]
    inputs[
        'sweepMode'] = sweepMode  # 0->k2k (T2),  1->02k (T1),  2->k20 (T2), 3->Niquist modulated (T2)
    inputs['phaseGradTime'] = phaseGradTime  # Phase and slice dephasing time
    inputs['rdPreemphasis'] = rdPreemphasis
    inputs['drfPhase'] = drfPhase
    inputs['dummyPulses'] = dummyPulses  # Dummy pulses for T1 stabilization
    inputs['shimming'] = shimming

    # Calculate the acquisition bandwidth
    if nPoints[0] > nPoints[1]:
        bandwidth = nPoints[0] / acqTimeMax
    else:
        bandwidth = nPoints[1] / acqTimeMax
    auxiliar['bandwidth'] = bandwidth

    # Oversampled BW
    BWov = bandwidth * oversamplingFactor
    samplingPeriod = 1 / BWov * 1e6

    # Calculate the angles of each normalized k-space line
    phi = np.array([0])
    while phi[-1] < np.pi:
        dPhi = np.array([
            (nPoints[1] + nPoints[0]) / (nPoints[0] * nPoints[1]) +
            np.abs(nPoints[1] - nPoints[0]) /
            (nPoints[0] * nPoints[1]) * np.cos(2 * phi[-1])
        ])
        phi = np.concatenate((phi, phi[-1] + dPhi), axis=0)
    nBlocks = np.size(phi) - 1
    phi = phi[0:nBlocks]
    phiEtlUnder = phi[0::etl * undersampling]
    alpha = np.pi / (phiEtlUnder[1] + phiEtlUnder[-1])
    phi = phiEtlUnder * alpha
    nBlocks = np.size(phi)
    del alpha, dPhi, phiEtlUnder

    # Calculate readout gradients (directions 0 and 1)
    rdGradAmp = bandwidth / (gammaB * fov)
    rdGradAmpArray = np.array(
        [rdGradAmp[0] * np.cos(phi), rdGradAmp[1] * np.sin(phi)])

    # Calculate the phase gradients (directions 0 and 1)
    phGradAmp = rdGradAmp / (bandwidth * (phaseGradTime + gradRiseTime))
    phGradAmpArray = np.array(
        [-phGradAmp[0] * np.sin(phi), phGradAmp[1] * np.cos(phi)])

    # Calculate the slice gradients and k-points (direction 2)
    if nPoints[2] > 1:
        slGradAmp = 1 / (resolution[2] * gammaB *
                         (phaseGradTime + gradRiseTime))
    else:
        slGradAmp = 0
    if nPoints[2] % 2 == 0:
        slGradAmpArray = np.linspace(-slGradAmp,
                                     slGradAmp,
                                     num=nPoints[2],
                                     endpoint=False)
        kSl = np.linspace(-kMax[2], kMax[2], num=nPoints[2], endpoint=False)
    else:
        slGradAmpArray = np.linspace(-slGradAmp,
                                     slGradAmp,
                                     num=nPoints[2],
                                     endpoint=True)
        kSl = np.linspace(-kMax[2], kMax[2], num=nPoints[2], endpoint=True)

    # Calculate the number of readouts and acqTime as a function of phi
    nrdx = nPoints[0] * np.abs(np.cos(phi))
    nrdy = nPoints[1] * np.abs(np.sin(phi))
    nrd = np.int32(np.round(np.sqrt(np.power(nrdx, 2) + np.power(nrdy, 2))))
    acqTime = nrd / bandwidth
    del nrdx, nrdy

    # Normalized kmax (time space)
    kMaxN = 1 / (2 * gammaB * resolution * rdGradAmp)

    # Create k-space and get phase gradients
    kPropellerX = np.array([])
    kPropellerY = np.array([])
    kPropellerZ = np.array([])
    phGradAmpBlock = {}
    ind = getIndex(etl, sweepMode)
    for blockIndex in range(nBlocks):
        if nrd[blockIndex] % 2 == 0:
            nprov = np.linspace(-1.0, 1.0, num=nrd[blockIndex], endpoint=False)
        else:
            nprov = np.linspace(-1.0, 1.0, num=nrd[blockIndex], endpoint=True)
        # Main lines in normalized k-space
        kLineN = np.array([
            nprov * np.cos(phi[blockIndex]) * kMaxN[0],
            nprov * np.sin(phi[blockIndex]) * kMaxN[1]
        ])
        # Add lines for propeller in normalized k-space
        dkN = np.array([
            kLineN[1, 1] - kLineN[1, 0], kLineN[0, 0] - kLineN[0, 1]
        ]) * undersampling
        for slIndex in range(nPoints[2]):
            for echoIndex in range(etl):
                # True k-space
                if etl % 2 == 0:
                    kLine = np.array([
                        (kLineN[0, :] - dkN[0] * (echoIndex - etl / 2)) *
                        gammaB * np.abs(rdGradAmp[0]),
                        (kLineN[1, :] - dkN[1] * (echoIndex - etl / 2)) *
                        gammaB * np.abs(rdGradAmp[1]),
                        np.ones(nrd[blockIndex]) * kSl[slIndex]
                    ])
                else:
                    kLine = np.array([
                        (kLineN[0, :] - dkN[0] * (echoIndex - (etl - 1) / 2)) *
                        gammaB * np.abs(rdGradAmp[0]),
                        (kLineN[1, :] - dkN[1] * (echoIndex - (etl - 1) / 2)) *
                        gammaB * np.abs(rdGradAmp[1]),
                        np.ones(nrd[blockIndex]) * kSl[slIndex]
                    ])
                # Save points into propeller k-points
                kPropellerX = np.concatenate((kPropellerX, kLine[0, :]),
                                             axis=0)
                kPropellerY = np.concatenate((kPropellerY, kLine[1, :]),
                                             axis=0)
                kPropellerZ = np.concatenate((kPropellerZ, kLine[2, :]),
                                             axis=0)
        # Define here all the phase gradients for current block
        if etl % 2 == 1:
            phGradAmpBlock[blockIndex] = np.array([
                np.linspace(
                    -(etl - 1) / 2, (etl - 1) / 2, num=etl, endpoint=True) *
                phGradAmpArray[0, blockIndex],
                np.linspace(
                    -(etl - 1) / 2, (etl - 1) / 2, num=etl, endpoint=True) *
                phGradAmpArray[1, blockIndex]
            ])
        else:
            phGradAmpBlock[blockIndex] = np.array([
                np.linspace(-etl / 2, etl / 2, num=etl, endpoint=False) *
                phGradAmpArray[0, blockIndex],
                np.linspace(-etl / 2, etl / 2, num=etl, endpoint=False) *
                phGradAmpArray[1, blockIndex]
            ])
        # Reorganize gradients according to the sweep mode
        phGradAmpBlock[blockIndex] = phGradAmpBlock[blockIndex][:, ind]
    del kLineN, kLine, dkN, nprov

    # Generate cartesian k-points
    if nPoints[0] % 2 == 1:
        kCartesianX = np.linspace(-kMax[0],
                                  kMax[0],
                                  num=nPoints[0],
                                  endpoint=True)
    else:
        kCartesianX = np.linspace(-kMax[0],
                                  kMax[0],
                                  num=nPoints[0],
                                  endpoint=False)
    if nPoints[1] % 2 == 1:
        kCartesianY = np.linspace(-kMax[1],
                                  kMax[1],
                                  num=nPoints[1],
                                  endpoint=True)
    else:
        kCartesianY = np.linspace(-kMax[1],
                                  kMax[1],
                                  num=nPoints[1],
                                  endpoint=False)
    if nPoints[2] % 2 == 1:
        kCartesianZ = np.linspace(-kMax[2],
                                  kMax[2],
                                  num=nPoints[2],
                                  endpoint=True)
    else:
        kCartesianZ = np.linspace(-kMax[2],
                                  kMax[2],
                                  num=nPoints[2],
                                  endpoint=False)
    kCartesianY, kCartesianZ, kCartesianX = np.meshgrid(
        kCartesianY, kCartesianZ, kCartesianX)
    kCartesianX = np.squeeze(
        np.reshape(kCartesianX, (1, nPoints[0] * nPoints[1] * nPoints[2])))
    kCartesianY = np.squeeze(
        np.reshape(kCartesianY, (1, nPoints[0] * nPoints[1] * nPoints[2])))
    kCartesianZ = np.squeeze(
        np.reshape(kCartesianZ, (1, nPoints[0] * nPoints[1] * nPoints[2])))
    if nPoints[2] == 1:
        kCartesianZ *= 0

    # Change gradient values to OCRA units
    gFactor = reorganizeGfactor(axes)
    rdGradAmpArray[0, :] = rdGradAmpArray[0, :] / gFactor[0] * 1000 / 10
    rdGradAmpArray[1, :] = rdGradAmpArray[1, :] / gFactor[1] * 1000 / 10
    slGradAmpArray = slGradAmpArray / gFactor[2] * 1000 / 10
    for blockIndex in range(nBlocks):
        phGradAmpBlock[blockIndex][
            0, :] = phGradAmpBlock[blockIndex][0, :] / gFactor[0] * 1000 / 10
        phGradAmpBlock[blockIndex][
            1, :] = phGradAmpBlock[blockIndex][1, :] / gFactor[1] * 1000 / 10

    # Create sequence
    def createSequence():
        nRepetitions = nBlocks * nPoints[2] + dummyPulses
        scanTime = nRepetitions * repetitionTime
        # Set shimming
        iniSequence(20, shimming)
        slIndex = 0
        blockIndex = 0
        for repeIndex in range(nRepetitions):
            # Initialize time
            tRep = 20e3 + inversionTime + repetitionTime * repeIndex

            # Inversion pulse
            if inversionTime != 0:
                t0 = tRep - inversionTime - rfReTime / 2 - blkTime
                rfPulse(t0, rfReTime, rfReAmp, 0)

            # Excitation pulse
            t0 = tRep - rfExTime / 2 - blkTime
            rfPulse(t0, rfExTime, rfExAmp, drfPhase * np.pi / 180)

            # Dephasing readout
            t0 = tRep + rfExTime / 2 - gradDelay
            rdPreX = rdP0 + rdPm * np.abs(rdGradAmpArray[0, blockIndex])
            rdPreY = rdP0 + rdPm * np.abs(rdGradAmpArray[1, blockIndex])
            if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                gradTrap(t0, nrd[blockIndex] / bandwidth + 2 * addRdGradTime,
                         rdGradAmpArray[0, blockIndex] / 2 * rdPreX, axes[0])
                gradTrap(t0, nrd[blockIndex] / bandwidth + 2 * addRdGradTime,
                         rdGradAmpArray[1, blockIndex] / 2 * rdPreY, axes[1])
#            if repeIndex>=dummyPulses:         # This is to account for dummy pulses
#                gradTrap(t0, nrd[blockIndex]/bandwidth+2*addRdGradTime, rdGradAmpArray[0,blockIndex]/2*rdPreemphasis, axes[0])
#                gradTrap(t0, nrd[blockIndex]/bandwidth+2*addRdGradTime, rdGradAmpArray[1,blockIndex]/2*rdPreemphasis, axes[1])

# Echo train
            for echoIndex in range(etl):
                tEcho = tRep + echoSpacing * (echoIndex + 1)

                # Refocusing pulse
                t0 = tEcho - echoSpacing / 2 - rfReTime / 2 - blkTime
                rfPulse(t0, rfReTime, rfReAmp, np.pi / 2)

                # Dephasing phase and slice gradients
                t0 = tEcho - echoSpacing / 2 + rfReTime / 2 - gradDelay
                if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                    gradTrap(t0, phaseGradTime,
                             phGradAmpBlock[blockIndex][0, echoIndex], axes[0])
                    gradTrap(t0, phaseGradTime,
                             phGradAmpBlock[blockIndex][1, echoIndex], axes[1])
                    gradTrap(t0, phaseGradTime, slGradAmpArray[slIndex],
                             axes[2])

                # Readout gradient
                if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                    if nrd[blockIndex] % 2 == 0:
                        t0 = tEcho - (nrd[blockIndex] + 1) / (
                            2 * bandwidth
                        ) - addRdGradTime - gradRiseTime - gradDelay
                        gradTrap(t0, (nrd[blockIndex] + 1) / bandwidth +
                                 2 * addRdGradTime,
                                 rdGradAmpArray[0, blockIndex], axes[0])
                        gradTrap(t0, (nrd[blockIndex] + 1) / bandwidth +
                                 2 * addRdGradTime,
                                 rdGradAmpArray[1, blockIndex], axes[1])
                    else:
                        t0 = tEcho - nrd[blockIndex] / (
                            2 * bandwidth
                        ) - addRdGradTime - gradRiseTime - gradDelay
                        gradTrap(
                            t0,
                            nrd[blockIndex] / bandwidth + 2 * addRdGradTime,
                            rdGradAmpArray[0, blockIndex], axes[0])
                        gradTrap(
                            t0,
                            nrd[blockIndex] / bandwidth + 2 * addRdGradTime,
                            rdGradAmpArray[1, blockIndex], axes[1])

                # Rx gate
                if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                    if nrd[blockIndex] % 2 == 0:
                        t0 = tEcho - (nrd[blockIndex] + 1) / (
                            2 * bandwidth) - addRdPoints / bandwidth - 1 / (
                                2 * bandwidth)
                    else:
                        t0 = tEcho - (nrd[blockIndex]) / (
                            2 * bandwidth) - addRdPoints / bandwidth - 1 / (
                                2 * bandwidth)
                    rxGate(t0, (nrd[blockIndex] + 2 * addRdPoints) / bandwidth)

                # Rephasing phase and slice gradients
                t0 = tEcho + nrd[blockIndex] / (
                    2 * bandwidth) + addRdGradTime + gradRiseTime
                if (echoIndex < etl - 1 and repeIndex >= dummyPulses):
                    gradTrap(t0, phaseGradTime,
                             -phGradAmpBlock[blockIndex][0, echoIndex],
                             axes[0])
                    gradTrap(t0, phaseGradTime,
                             -phGradAmpBlock[blockIndex][1, echoIndex],
                             axes[1])
                    gradTrap(t0, phaseGradTime, -slGradAmpArray[slIndex],
                             axes[2])

            # Update the block and slice index
            if repeIndex >= dummyPulses:
                if slIndex == nPoints[2] - 1:
                    blockIndex += 1
                    slIndex = 0
                else:
                    slIndex += 1

            if repeIndex == nRepetitions:
                endSequence(scanTime)

    # Frequency calibration function
    def createFreqCalSequence():
        t0 = 20

        # Shimming
        iniSequence(t0, shimming)

        # Excitation pulse
        rfPulse(t0, rfExTime, rfExAmp, drfPhase * np.pi / 180)

        # Refocusing pulse
        t0 += rfExTime / 2 + echoSpacing / 2 - rfReTime / 2
        rfPulse(t0, rfReTime, rfReAmp, np.pi / 2)

        # Rx
        t0 += blkTime + rfReTime / 2 + echoSpacing / 2 - acqTimeFreqCal / 2 - addRdPoints / bandwidth
        rxGate(t0, acqTimeFreqCal + 2 * addRdPoints / bandwidth)

        # Finalize sequence
        endSequence(repetitionTime)

    def rfPulse(tStart, rfTime, rfAmplitude, rfPhase):
        txTime = np.array([tStart + blkTime, tStart + blkTime + rfTime])
        txAmp = np.array([rfAmplitude * np.exp(1j * rfPhase), 0.])
        txGateTime = np.array([tStart, tStart + blkTime + rfTime])
        txGateAmp = np.array([1, 0])
        expt.add_flodict({
            'tx0': (txTime, txAmp),
            'tx_gate': (txGateTime, txGateAmp)
        })

    def rxGate(tStart, gateTime):
        rxGateTime = np.array([tStart, tStart + gateTime])
        rxGateAmp = np.array([1, 0])
        expt.add_flodict({
            'rx0_en': (rxGateTime, rxGateAmp),
            'rx_gate': (rxGateTime, rxGateAmp),
        })

    def gradTrap(tStart, gTime, gAmp, gAxis):
        tUp = np.linspace(tStart,
                          tStart + gradRiseTime,
                          num=gSteps,
                          endpoint=False)
        tDown = tUp + gradRiseTime + gTime
        t = np.concatenate((tUp, tDown), axis=0)
        dAmp = gAmp / gSteps
        aUp = np.linspace(dAmp, gAmp, num=gSteps)
        aDown = np.linspace(gAmp - dAmp, 0, num=gSteps)
        a = np.concatenate((aUp, aDown), axis=0)
        if gAxis == 0:
            expt.add_flodict({'grad_vx': (t, a + shimming[0])})
        elif gAxis == 1:
            expt.add_flodict({'grad_vy': (t, a + shimming[1])})
        elif gAxis == 2:
            expt.add_flodict({'grad_vz': (t, a + shimming[2])})

    def endSequence(tEnd):
        expt.add_flodict({
            'grad_vx': (np.array([tEnd]), np.array([0])),
            'grad_vy': (np.array([tEnd]), np.array([0])),
            'grad_vz': (np.array([tEnd]), np.array([0])),
        })

    def iniSequence(tEnd, shimming):
        expt.add_flodict({
            'grad_vx': (np.array([tEnd]), np.array([shimming[0]])),
            'grad_vy': (np.array([tEnd]), np.array([shimming[1]])),
            'grad_vz': (np.array([tEnd]), np.array([shimming[2]])),
        })

    # Changing time parameters to us
    rfExTime = rfExTime * 1e6
    rfReTime = rfReTime * 1e6
    echoSpacing = echoSpacing * 1e6
    repetitionTime = repetitionTime * 1e6
    gradRiseTime = gradRiseTime * 1e6
    phaseGradTime = phaseGradTime * 1e6
    inversionTime = inversionTime * 1e6
    bandwidth = bandwidth * 1e-6

    # Calibrate frequency
    expt = ex.Experiment(lo_freq=larmorFreq,
                         rx_t=samplingPeriod,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    samplingPeriod = expt.get_rx_ts()[0]
    bandwidth = 1 / samplingPeriod / oversamplingFactor
    acqTimeFreqCal = nPoints[0] / bandwidth  # us
    auxiliar['bandwidth'] = bandwidth * 1e6
    createFreqCalSequence()
    rxd, msgs = expt.run()
    dataFreqCal = sig.decimate(rxd['rx0'] * 13.788,
                               oversamplingFactor,
                               ftype='fir',
                               zero_phase=True)
    dataFreqCal = dataFreqCal[addRdPoints:nPoints[0] + addRdPoints]
    # Plot fid
    plt.figure(1)
    tVector = np.linspace(
        -acqTimeFreqCal / 2, acqTimeFreqCal / 2, num=nPoints[0],
        endpoint=True) * 1e-3
    plt.subplot(1, 2, 1)
    plt.plot(tVector, np.abs(dataFreqCal))
    plt.title("Signal amplitude")
    plt.xlabel("Time (ms)")
    plt.ylabel("Amplitude (mV)")
    plt.subplot(1, 2, 2)
    angle = np.unwrap(np.angle(dataFreqCal))
    plt.title("Signal phase")
    plt.xlabel("Time (ms)")
    plt.ylabel("Phase (rad)")
    plt.plot(tVector, angle)
    # Get larmor frequency
    dPhi = angle[-1] - angle[0]
    df = dPhi / (2 * np.pi * acqTimeFreqCal)
    larmorFreq += df
    auxiliar['larmorFreq'] = larmorFreq * 1e6
    print("f0 = %s MHz" % (round(larmorFreq, 5)))
    # Plot sequence:
    #    expt.plot_sequence()
    #    plt.show()
    # Delete experiment:
    expt.__del__()

    # Create full sequence
    expt = ex.Experiment(lo_freq=larmorFreq,
                         rx_t=samplingPeriod,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    samplingPeriod = expt.get_rx_ts()[0]
    bandwidth = 1 / samplingPeriod / oversamplingFactor
    auxiliar['bandwidth'] = bandwidth * 1e6
    createSequence()

    # Plot sequence:
    #    expt.plot_sequence()
    #    plt.show()

    # Run the experiment
    seqTime = nPoints[2] * nBlocks * repetitionTime * 1e-6 * nScans
    print("Expected scan time = %s s" % (round(seqTime, 0)))
    print("Runing sequence...")
    tStart = time.time()
    dataFull = []
    for ii in range(nScans):
        rxd, msgs = expt.run()
        rxd['rx0'] = rxd[
            'rx0'] * 13.788  # Here I normalize to get the result in mV
        # Get data
        scanData = sig.decimate(rxd['rx0'],
                                oversamplingFactor,
                                ftype='fir',
                                zero_phase=True)
        dataFull = np.concatenate((dataFull, scanData), axis=0)
    expt.__del__()
    tEnd = time.time()
    print("True scan time = %s s" % (round(tEnd - tStart, 0)))

    # Average data
    print("Averaging data...")
    nrdTotal = np.sum(nrd + 2 * addRdPoints) * etl
    dataProvA = np.reshape(dataFull, (nScans, nrdTotal * nPoints[2]))
    dataProvA = np.average(dataProvA, axis=0)

    # Reorganize data according to sweep mode
    print("Reorganizing data according to sweep mode...")
    dataProvB = np.zeros(np.size(dataProvA), dtype=complex)
    n0 = 0
    n1 = 0
    for blockIndex in range(nBlocks):
        n1 += nPoints[2] * etl * (nrd[blockIndex] + 2 * addRdPoints)
        dataProvC = np.reshape(
            dataProvA[n0:n1],
            (nPoints[2], etl, nrd[blockIndex] + 2 * addRdPoints))
        dataProvD = dataProvC * 0
        for ii in range(etl):
            dataProvD[:, ind[ii], :] = dataProvC[:, ii, :]
        dataProvD = np.reshape(dataProvD,
                               (1, nPoints[2] * etl *
                                (nrd[blockIndex] + 2 * addRdPoints)))
        dataProvB[n0:n1] = dataProvD
        n0 = n1
    del dataProvC, dataProvD, n0, n1

    # Delete the additional rd points and fix echo delay!!
    print("Deleting additional readout points...")
    dataPropeller = np.zeros(nrdTotal * nPoints[2] -
                             2 * addRdPoints * nPoints[2] * nBlocks * etl,
                             dtype=complex)
    n0 = 0
    n1 = 0
    n2 = 0
    n3 = 0
    for blockIndex in range(nBlocks):
        n1 += nPoints[2] * etl * (nrd[blockIndex] + 2 * addRdPoints)
        n3 += nPoints[2] * etl * (nrd[blockIndex])
        dataProvC = np.reshape(
            dataProvB[n0:n1],
            (nPoints[2], etl, nrd[blockIndex] + 2 * addRdPoints))
        if etl % 2 == 0:  # Asumo que nPoints[2] es par
            k0Line = dataProvC[int((nPoints[2] - 1) / 2), int(etl / 2), :]
        else:
            k0Line = dataProvC[int((nPoints[2] - 1) / 2),
                               int((etl - 1) / 2), :]
        k0 = np.argmax(np.abs(k0Line))
        #        k0 = int((nrd[blockIndex]+2*addRdPoints)/2-2)
        if nrd[blockIndex] % 2 == 0:
            dataProvC = dataProvC[:, :, k0 - int(nrd[blockIndex] / 2):k0 +
                                  int(nrd[blockIndex] / 2)]
        else:
            dataProvC = dataProvC[:, :,
                                  k0 - int((nrd[blockIndex] - 1) / 2):k0 +
                                  int((nrd[blockIndex] + 1) / 2)]
        dataProvC = np.reshape(dataProvC,
                               (1, nPoints[2] * etl * nrd[blockIndex]))
        dataPropeller[n2:n3] = dataProvC
        n0 = n1
        n2 = n3
    del dataProvA, dataProvB, dataProvC, n0, n1, n2, n3

    # Regridding to cartesian k-space
    #    print("Regridding to cartesian grid...")
    #    tStart = time.time()
    #    if nPoints[2]==1:
    #        dataCartesian = gd((kPropellerX, kPropellerY), dataPropeller, (kCartesianX, kCartesianY), method='linear', fill_value=0.)
    #    else:
    #        dataCartesian = gd((kPropellerX, kPropellerY, kPropellerZ), dataPropeller, (kCartesianX, kCartesianY, kCartesianZ), method='linear', fill_value=0.)
    #    tEnd = time.time()
    #    print("Regridding done in = %s s" %(round(tEnd-tStart, 0)))
    kPropeller = np.array(
        [kPropellerX, kPropellerY, kPropellerZ, dataPropeller])
    #    kCartesian = np.array([kCartesianX, kCartesianY, kCartesianZ, dataCartesian])
    kCartesian = np.array([kCartesianX, kCartesianY, kCartesianZ])
    del kCartesianX, kCartesianY, kCartesianZ, kPropellerX, kPropellerY, kPropellerZ, dataPropeller
    auxiliar['kMax'] = kMax
    kSpace['sampled'] = np.transpose(kCartesian)
    kSpace['sampledNonCart'] = np.transpose(kPropeller)
    print("Done!")

    #    # Get image with FFT
    #    dataCartesian = np.reshape(dataCartesian, (nPoints[2], nPoints[1], nPoints[0]))
    #    img = np.fft.ifftshift(np.fft.ifftn(np.fft.ifftshift(dataCartesian)))
    #    kSpace['image'] = img

    # Save data
    dt = datetime.now()
    dt_string = dt.strftime("%Y.%m.%d.%H.%M.%S")
    dt2 = date.today()
    dt2_string = dt2.strftime("%Y.%m.%d")
    if not os.path.exists('experiments/acquisitions/%s' % (dt2_string)):
        os.makedirs('experiments/acquisitions/%s' % (dt2_string))

    if not os.path.exists('experiments/acquisitions/%s/%s' %
                          (dt2_string, dt_string)):
        os.makedirs('experiments/acquisitions/%s/%s' % (dt2_string, dt_string))
    inputs['name'] = "%s.%s.mat" % ("TSE", dt_string)
    auxiliar['fileName'] = "%s.%s.mat" % ("PROPELLER STACK", dt_string)
    rawData['inputs'] = inputs
    rawData['auxiliar'] = auxiliar
    rawData['kSpace'] = kSpace
    rawdata = {}
    rawdata['rawData'] = rawData
    savemat(
        "experiments/acquisitions/%s/%s/%s.%s.mat" %
        (dt2_string, dt_string, "PROPELLER STACK", dt_string), rawdata)
Пример #24
0
def rabi_flops(
        lo_freq=3.041,  # MHz
        rf_amp=0.62,  # 1 = full-scale
        N=10,
        step=5,
        rf_pi2_duration0=50,  # us
        tr_duration=20e3,
        echo_duration=15e3,  # delay after end of RX before start of next TR
        BW=31,  # us, 3.333us, 300 kHz rate
        rx_wait=100,
        readout_duration=10e3):

    ## All times are in the context of a single TR, starting at time 0
    init_gpa = True

    rx_period = 1 / (BW * 1e-3)

    expt = ex.Experiment(lo_freq=lo_freq,
                         rx_t=rx_period,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))

    ##########################################################

    def rf_wf(tstart, echo_idx, k):
        rf_pi2_duration = rf_pi2_duration0 + k
        rf_pi_duration = rf_pi2_duration * 2
        pi2_phase = 1  # x
        pi_phase = 1j  # y
        if echo_idx == 0:
            # do pi/2 pulse, then start first pi pulse
            return np.array([
                tstart + (echo_duration - rf_pi2_duration) / 2,
                tstart + (echo_duration + rf_pi2_duration) / 2,
                tstart + echo_duration - rf_pi_duration / 2
            ]), np.array([pi2_phase * rf_amp, 0, pi_phase * rf_amp])
        else:
            # finish last pi pulse, start next pi pulse
            return np.array([tstart + rf_pi_duration / 2]), np.array([0])

    #######################################################################

    def tx_gate_wf(tstart, echo_idx):
        tx_gate_pre = 15  # us, time to start the TX gate before each RF pulse begins
        tx_gate_post = 1  # us, time to keep the TX gate on after an RF pulse ends
        rf_pi2_duration = rf_pi2_duration0 + k
        rf_pi_duration = rf_pi2_duration * 2
        if echo_idx == 0:
            # do pi/2 pulse, then start first pi pulse
            return np.array([tstart + (echo_duration - rf_pi2_duration)/2 - tx_gate_pre,
                             tstart + (echo_duration + rf_pi2_duration)/2 + tx_gate_post,
                             tstart + echo_duration - rf_pi_duration/2 - tx_gate_pre]), \
                             np.array([1, 0, 1])
        else:
            # finish last pi pulse, start next pi pulse
            return np.array([tstart + rf_pi_duration / 2 + tx_gate_post
                             ]), np.array([0])

    ##############################################################

    def readout_wf(tstart, echo_idx, k):
        rf_pi2_duration = rf_pi2_duration0 + k
        rf_pi_duration = rf_pi2_duration * 2
        if echo_idx != 0:
            return np.array([
                tstart + rf_pi_duration / 2 + rx_wait,
                tstart + +rf_pi_duration / 2 + rx_wait + readout_duration
            ]), np.array([1, 0])
        else:
            return np.array([tstart]), np.array([0])  # keep on zero otherwise

    ##############################################################

    global_t = 20  # start the first TR at 20us
    k = 0
    i = 0
    while i < N:

        #        if fid==1:
        #            rf_tend = rf_tstart + rf_duration+k # us
        #            rx_tstart = rf_tend+rx_wait # us
        #            rx_tend = rx_tstart + readout_duration  # us
        #            expt.add_flodict({
        #                # second tx0 pulse purely for loopback debugging
        #                'tx0': ( np.array([rf_tstart, rf_tend])+tstart, np.array([rf_amp,0]) ),
        #                'rx0_en': ( np.array([rx_tstart, rx_tend])+tstart, np.array([1, 0]) ),
        #                'tx_gate': ( np.array([rf_tstart - tx_gate_pre, rf_tend + tx_gate_post])+tstart, np.array([1, 0]) ),
        #                'rx_gate': ( np.array([rx_tstart, rx_tend])+tstart, np.array([1, 0]) )
        #            })
        #            tstart = tstart + rx_tend+tr_wait
        #        else:

        for echo_idx in range(2):
            tx_t, tx_a = rf_wf(global_t, echo_idx, k)
            tx_gate_t, tx_gate_a = tx_gate_wf(global_t, echo_idx)
            readout_t, readout_a = readout_wf(global_t, echo_idx, k)
            rx_gate_t, rx_gate_a = readout_wf(global_t, echo_idx, k)

            expt.add_flodict({
                'tx0': (tx_t, tx_a),
                'rx0_en': (readout_t, readout_a),
                'tx_gate': (tx_gate_t, tx_gate_a),
                'rx_gate': (rx_gate_t, rx_gate_a),
            })
            global_t += echo_duration

        global_t += tr_duration - echo_duration

        i = i + 1
        k = k + step

    expt.plot_sequence()
    plt.show()

    rxd, msg = expt.run()
    plt.plot(rxd['rx0'])
    plt.show()

    expt.__del__()
    return rxd['rx0']
    return results


if __name__ == "__main__":
    MAX_PIXEL_VALUE = 177.0  # this is usually 256.0 but in our case because of the lighting in our renders, it is lower

    experiment = exp.Experiment(name="TestShape",
                                experiment_method=run_shape_experiment,
                                sampler=['mh'],
                                input_file=['test2'],
                                results_folder='./results',
                                data_folder='./data/',
                                max_part_count=10,
                                max_pixel_value=MAX_PIXEL_VALUE,
                                ll_variance=[0.0001],
                                change_size_variance=[0.00005],
                                move_part_variance=[0.00005],
                                change_viewpoint_variance=[10.0],
                                burn_in=5000,
                                sample_count=10,
                                best_sample_count=10,
                                thinning_period=10000,
                                report_period=10000)

    experiment.run(parallel=False, num_processes=1)

    print(experiment.results)
    experiment.save('./results')
    experiment.append_csv('./results/TestShape.csv')
Пример #26
0
import experiment as xp
import data
import classif
x = xp.Experiment(data.Data(
    100, 3, 4), [xp.KNN(), xp.LDA(),
                 xp.QDA(), classif.Cuadratico()])

print('[xp.KNN(), xp.LDA(), xp.QDA(), classif.Cuadratico()]')
print(x.accuracys)
    MAX_PIXEL_VALUE = 177.0  # this is usually 256.0 but in our case because of the lighting in our renders, it is lower

    # the experiment class allows you to run multiple chains (either in parallel or consecutively) and save all the
    # results. You don't need to use it but it will make it easier to run the chain for many images
    # below are the parameters used for the results in the paper. You may need to tune them for your stimuli.
    experiment = exp.Experiment(
        name="TestExperiment",
        experiment_method=run_bdaooss_experiment,
        sampler=['mh'],
        input_file=input_files,
        results_folder='./results',
        data_folder='./data/',
        # set to False if you'd like to see hypotheses rendered in real-time.
        # note this will slow down the chain significantly.
        offscreen_rendering=True,
        max_depth=5,  # maximum depth for shape trees
        max_pixel_value=MAX_PIXEL_VALUE,
        ll_variance=[0.0001],  # likelihood variance
        change_size_variance=[0.00005],  # variance for change size move
        change_viewpoint_variance=[10.0],  # variance for change viewpoint move
        # chain parameters
        burn_in=5000,
        sample_count=10,
        best_sample_count=10,
        thinning_period=10000,
        report_period=1000)

    # run the experiment. if you'd like to run chains for multiple input files at the same time taking advantage of
    # multiprocessing, set parallel=True. num_processes determines the number of processes running in parallel.
    experiment.run(parallel=False, num_processes=-1)
Пример #28
0
def haste_standalone(
    init_gpa=False,  # Starts the gpa
    nScans=1,  # NEX
    larmorFreq=3.07547,  # MHz, Larmor frequency
    rfExAmp=0.058,  # a.u., rf excitation pulse amplitude
    rfReAmp=2 * 0.058,  # a.u., rf refocusing pulse amplitude
    rfExTime=170,  # us, rf excitation pulse time
    rfReTime=170,  # us, rf refocusing pulse time
    rfEnvelope='Rec',  # 'Rec' -> square pulse, 'Sinc' -> sinc pulse
    echoSpacing=10.,  # ms, time between echoes
    inversionTime=0.,  # ms, Inversion recovery time
    repetitionTime=700.,  # ms, TR
    fov=np.array([120., 120., 20.]),  # mm, FOV along readout, phase and slice
    dfov=np.array([0., 0., 0.]),  # mm, displacement of fov center
    nPoints=np.array([60, 60,
                      1]),  # Number of points along readout, phase and slice
    acqTime=4,  # ms, acquisition time
    axes=np.array([0, 2, 1]),  # 0->x, 1->y and 2->z defined as [rd,ph,sl]
    axesEnable=np.array([1, 1, 1]),  # 1-> Enable, 0-> Disable
    sweepMode=1,  # 0->k2k (T2),  1->02k (T1),  2->k20 (T2), 3->Niquist modulated (T2)
    rdGradTime=4.5,  # ms, readout gradient time
    rdDephTime=1,  # ms, readout dephasing time
    phGradTime=1,  # ms, phase and slice dephasing time
    rdPreemphasis=1.00,  # readout dephasing gradient is multiplied by this factor
    ssPreemphasis=1,  # ssGradAmplitue is multiplied by this number for rephasing
    crusherDelay=0,  # us, delay of the crusher gradient
    drfPhase=0,  # degrees, phase of the excitation pulse
    dummyPulses=1,  # number of dummy pulses for T1 stabilization
    shimming=np.array([-70., -90.,
                       10.]),  # a.u.*1e4, shimming along the X,Y and Z axes
    parFourierFraction=1.0  # fraction of acquired k-space along phase direction
):

    freqCal = True
    demo = False

    # rawData fields
    rawData = {}

    # Conversion of variables to non-multiplied units
    larmorFreq = larmorFreq * 1e6
    rfExTime = rfExTime * 1e-6
    rfReTime = rfReTime * 1e-6
    fov = np.array(fov) * 1e-3
    dfov = np.array(dfov) * 1e-3
    echoSpacing = echoSpacing * 1e-3
    acqTime = acqTime * 1e-3
    shimming = np.array(shimming) * 1e-4
    repetitionTime = repetitionTime * 1e-3
    inversionTime = inversionTime * 1e-3
    rdGradTime = rdGradTime * 1e-3
    rdDephTime = rdDephTime * 1e-3
    phGradTime = phGradTime * 1e-3
    crusherDelay = crusherDelay * 1e-6

    # Inputs for rawData
    rawData['seqName'] = 'HASTE'
    rawData['nScans'] = nScans
    rawData['larmorFreq'] = larmorFreq  # Larmor frequency
    rawData['rfExAmp'] = rfExAmp  # rf excitation pulse amplitude
    rawData['rfReAmp'] = rfReAmp  # rf refocusing pulse amplitude
    rawData['rfExTime'] = rfExTime  # rf excitation pulse time
    rawData['rfReTime'] = rfReTime  # rf refocusing pulse time
    rawData['rfEnvelope'] = rfEnvelope
    rawData['echoSpacing'] = echoSpacing  # time between echoes
    rawData['inversionTime'] = inversionTime  # Inversion recovery time
    rawData['repetitionTime'] = repetitionTime  # TR
    rawData['fov'] = fov  # FOV along readout, phase and slice
    rawData['dfov'] = dfov  # Displacement of fov center
    rawData[
        'nPoints'] = nPoints  # Number of points along readout, phase and slice
    rawData['acqTime'] = acqTime  # Acquisition time
    rawData[
        'axesOrientation'] = axes  # 0->x, 1->y and 2->z defined as [rd,ph,sl]
    rawData['axesEnable'] = axesEnable  # 1-> Enable, 0-> Disable
    rawData[
        'sweepMode'] = sweepMode  # 0->k2k (T2),  1->02k (T1),  2->k20 (T2), 3->Niquist modulated (T2)
    rawData['rdPreemphasis'] = rdPreemphasis
    rawData['ssPreemphasis'] = ssPreemphasis
    rawData['drfPhase'] = drfPhase
    rawData['dummyPulses'] = dummyPulses  # Dummy pulses for T1 stabilization
    rawData['partialFourierFraction'] = parFourierFraction
    rawData['rdDephTime'] = rdDephTime
    rawData['crusherDelay'] = crusherDelay
    rawData['shimming'] = shimming

    # Miscellaneous
    slThickness = fov[2]
    rfSincLobes = 7  # Number of lobes for sinc rf excitation, BW = rfSincLobes/rfTime
    larmorFreq = larmorFreq * 1e-6
    gradRiseTime = 200e-6  # Estimated gradient rise time
    gSteps = int(gradRiseTime * 1e6 / 5)
    addRdPoints = 10  # Initial rd points to avoid artifact at the begining of rd
    if rfReAmp == 0:
        rfReAmp = 2 * rfExAmp
    if rfReTime == 0:
        rfReTime = rfExTime
    resolution = fov / nPoints
    rawData['resolution'] = resolution
    rawData['gradRiseTime'] = gradRiseTime
    rawData['addRdPoints'] = addRdPoints

    # Matrix size
    nRD = nPoints[0] + 2 * addRdPoints
    nPH = nPoints[1] * axesEnable[1] + (1 - axesEnable[1])

    # parAcqLines
    nPHreal = int(nPoints[1] * parFourierFraction)
    parAcqLines = int(nPHreal - nPoints[1] / 2)
    rawData['parAcqLines'] = parAcqLines
    print(parAcqLines)
    del nPHreal

    # BW
    BW = nPoints[0] / acqTime * 1e-6
    BWov = BW * hw.oversamplingFactor
    samplingPeriod = 1 / BWov
    rawData['samplingPeriod'] = samplingPeriod

    # Readout gradient time
    if rdGradTime < acqTime:
        rdGradTime = acqTime
    rawData['rdGradTime'] = rdGradTime

    # Phase de- and re-phasing time
    if phGradTime == 0 or phGradTime > echoSpacing / 2 - rfExTime / 2 - rfReTime / 2 - 2 * gradRiseTime:
        phGradTime = echoSpacing / 2 - rfExTime / 2 - rfReTime / 2 - 2 * gradRiseTime
    rawData['phGradTime'] = phGradTime

    # Slice selection dephasing gradient time
    ssDephGradTime = (rfExTime - gradRiseTime) / 2
    rawData['ssDephGradTime'] = ssDephGradTime

    # Max redaout and phase gradient amplitude
    rdGradAmplitude = nPoints[0] / (hw.gammaB * fov[0] *
                                    acqTime) * axesEnable[0]
    phGradAmplitude = nPH / (2 * hw.gammaB * fov[1] *
                             (phGradTime + gradRiseTime)) * axesEnable[1]
    rawData['rdGradAmplitude'] = rdGradAmplitude
    rawData['phGradAmplitude'] = phGradAmplitude

    # Slice selection gradient
    if rfEnvelope == 'Sinc':
        ssGradAmplitude = rfSincLobes / (hw.gammaB * slThickness *
                                         rfExTime) * axesEnable[2]
    elif rfEnvelope == 'Rec':
        ssGradAmplitude = 1 / (hw.gammaB * slThickness *
                               rfExTime) * axesEnable[2]
    rawData['ssGradAmplitude'] = ssGradAmplitude

    # Readout dephasing amplitude
    rdDephAmplitude = 0.5 * rdGradAmplitude * (gradRiseTime + rdGradTime) / (
        gradRiseTime + rdDephTime)
    rawData['rdDephAmplitude'] = rdDephAmplitude

    # Phase gradient vector
    phGradients = np.linspace(-phGradAmplitude,
                              phGradAmplitude,
                              num=nPH,
                              endpoint=False)

    # Get phase indexes for the given sweep mode
    ind = mri.getIndex(2 * parAcqLines, 2 * parAcqLines, sweepMode)
    ind = ind - parAcqLines + int(nPH / 2)
    ind = np.int32(
        np.concatenate((ind,
                        np.linspace(int(nPH / 2) - parAcqLines - 1,
                                    -1,
                                    num=int(nPH / 2) - parAcqLines,
                                    endpoint=False)),
                       axis=0))
    rawData['sweepOrder'] = ind

    # Now fix the number of phases to partailly acquired k-space
    nPH = (int(nPoints[1] / 2) + parAcqLines) * axesEnable[1] + (1 -
                                                                 axesEnable[1])
    phGradients = phGradients[0:nPH]
    phGradients = phGradients[ind]
    rawData['phGradients'] = phGradients

    def createSequenceDemo():
        nRepetitions = int(1 + dummyPulses)
        scanTime = 20e3 + nRepetitions * repetitionTime
        rawData['scanTime'] = scanTime * 1e-6
        acqPoints = 0
        data = []
        for repeIndex in range(nRepetitions):
            for echoIndex in range(nPH):
                if (repeIndex == 0 or repeIndex >= dummyPulses):
                    acqPoints += nRD * hw.oversamplingFactor
                    data = np.concatenate(
                        (data, np.random.randn(nRD * hw.oversamplingFactor) +
                         1j * np.random.randn(nRD * hw.oversamplingFactor)),
                        axis=0)
        return data, acqPoints

    def createSequence():
        nRepetitions = int(1 + dummyPulses)
        scanTime = 20e3 + nRepetitions * repetitionTime
        rawData['scanTime'] = scanTime * 1e-6
        print('Scan Time = ', (scanTime * 1e-6), 's')
        if rdGradTime == 0:  # Check if readout gradient is dc or pulsed
            dc = True
        else:
            dc = False

        # Set shimming
        mri.iniSequence(expt, 20, shimming)
        for repeIndex in range(nRepetitions):
            # Initialize time
            tEx = 20e3 + repetitionTime * repeIndex + inversionTime

            # Inversion pulse
            if repeIndex >= dummyPulses and inversionTime != 0:
                t0 = tEx - inversionTime - rfReTime / 2 - hw.blkTime
                mri.rfRecPulse(expt, t0, rfReTime, rfReAmp / 180 * 180, 0)
                mri.gradTrap(expt, t0 + hw.blkTime + rfReTime, gradRiseTime,
                             inversionTime * 0.5, 0.005, gSteps, axes[0],
                             shimming)
                mri.gradTrap(expt, t0 + hw.blkTime + rfReTime, gradRiseTime,
                             inversionTime * 0.5, 0.005, gSteps, axes[1],
                             shimming)
                mri.gradTrap(expt, t0 + hw.blkTime + rfReTime, gradRiseTime,
                             inversionTime * 0.5, 0.005, gSteps, axes[2],
                             shimming)

            # DC radout gradient if desired
            if (repeIndex == 0 or repeIndex >= dummyPulses) and dc == True:
                t0 = tEx - rfExTime / 2 - gradRiseTime - hw.gradDelay
                mri.gradTrap(expt, t0, echoSpacing * (nPH + 1),
                             rdGradAmplitude, axes[0])

            # Slice selection gradient dephasing
            if (slThickness != 0 and repeIndex >= dummyPulses):
                t0 = tEx - rfExTime / 2 - gradRiseTime - hw.gradDelay
                mri.gradTrap(expt, t0, gradRiseTime, rfExTime, ssGradAmplitude,
                             gSteps, axes[2], shimming)

            # Excitation pulse
            t0 = tEx - hw.blkTime - rfExTime / 2
            if rfEnvelope == 'Rec':
                mri.rfRecPulse(expt, t0, rfExTime, rfExAmp,
                               drfPhase * np.pi / 180)
            elif rfEnvelope == 'Sinc':
                mri.rfSincPulse(expt, t0, rfExTime, rfSincLobes, rfExAmp,
                                drfPhase * np.pi / 180)

            # Slice selection gradient rephasing
            if (slThickness != 0 and repeIndex >= dummyPulses):
                t0 = tEx + rfExTime / 2 + gradRiseTime - hw.gradDelay
                if rfEnvelope == 'Rec':
                    mri.gradTrap(expt, t0, gradRiseTime, 0.,
                                 -ssGradAmplitude * ssPreemphasis, gSteps,
                                 axes[2], shimming)
                elif rfEnvelope == 'Sinc':
                    mri.gradTrap(expt, t0, gradRiseTime, ssDephGradTime,
                                 -ssGradAmplitude * ssPreemphasis, gSteps,
                                 axes[2], shimming)

            # Dephasing readout
            t0 = tEx + rfExTime / 2 - hw.gradDelay
            if (repeIndex == 0 or repeIndex >= dummyPulses) and dc == False:
                mri.gradTrap(expt, t0, gradRiseTime, rdDephTime,
                             rdDephAmplitude * rdPreemphasis, gSteps, axes[0],
                             shimming)

            # Echo train
            for echoIndex in range(nPH):
                tEcho = tEx + echoSpacing * (echoIndex + 1)

                # Crusher gradient
                if repeIndex >= dummyPulses:
                    t0 = tEcho - echoSpacing / 2 - rfReTime / 2 - gradRiseTime - hw.gradDelay - crusherDelay
                    mri.gradTrap(expt, t0, gradRiseTime,
                                 rfReTime + 2 * crusherDelay, ssGradAmplitude,
                                 gSteps, axes[2], shimming)

                # Refocusing pulse
                t0 = tEcho - echoSpacing / 2 - rfReTime / 2 - hw.blkTime
                if rfEnvelope == 'Rec':
                    mri.rfRecPulse(expt, t0, rfReTime, rfReAmp,
                                   np.pi / 2 + drfPhase * np.pi / 180)
                if rfEnvelope == 'Sinc':
                    mri.rfSincPulse(expt, t0, rfReTime, rfSincLobes, rfReAmp,
                                    np.pi / 2 + drfPhase * np.pi / 180)

                # Dephasing phase gradient
                t0 = tEcho - echoSpacing / 2 + rfReTime / 2 - hw.gradDelay
                if repeIndex >= dummyPulses:  # This is to account for dummy pulses
                    mri.gradTrap(expt, t0, gradRiseTime, phGradTime,
                                 phGradients[echoIndex], gSteps, axes[1],
                                 shimming)

                # Readout gradient
                t0 = tEcho - rdGradTime / 2 - gradRiseTime - hw.gradDelay
                if (repeIndex == 0 or repeIndex >= dummyPulses
                    ) and dc == False:  # This is to account for dummy pulses
                    mri.gradTrap(expt, t0, gradRiseTime, rdGradTime,
                                 rdGradAmplitude, gSteps, axes[0], shimming)

                # Rx gate
                if (repeIndex == 0 or repeIndex >= dummyPulses):
                    t0 = tEcho - acqTime / 2 - addRdPoints / BW
                    mri.rxGate(expt, t0, acqTime + 2 * addRdPoints / BW)

                # Rephasing phase and slice gradients
                t0 = tEcho + acqTime / 2 + addRdPoints / BW - hw.gradDelay
                if (echoIndex < nPH - 1 and repeIndex >= dummyPulses):
                    mri.gradTrap(expt, t0, gradRiseTime, phGradTime,
                                 -phGradients[echoIndex], gSteps, axes[1],
                                 shimming)
                elif (echoIndex == nPH - 1 and repeIndex >= dummyPulses):
                    mri.gradTrap(expt, t0, gradRiseTime, phGradTime,
                                 +phGradients[echoIndex], gSteps, axes[1],
                                 shimming)

            if repeIndex == nRepetitions - 1:
                mri.endSequence(expt, scanTime)

    # Changing time parameters to us
    rfExTime = rfExTime * 1e6
    rfReTime = rfReTime * 1e6
    echoSpacing = echoSpacing * 1e6
    repetitionTime = repetitionTime * 1e6
    gradRiseTime = gradRiseTime * 1e6
    phGradTime = phGradTime * 1e6
    rdGradTime = rdGradTime * 1e6
    rdDephTime = rdDephTime * 1e6
    inversionTime = inversionTime * 1e6
    crusherDelay = crusherDelay * 1e6
    ssDephGradTime = ssDephGradTime * 1e6

    # Calibrate frequency
    if not demo and freqCal:
        mri.freqCalibration(rawData, bw=0.05)
        mri.freqCalibration(rawData, bw=0.005)
        larmorFreq = rawData['larmorFreq'] * 1e-6

    # Create full sequence
    if not demo:
        expt = ex.Experiment(lo_freq=larmorFreq,
                             rx_t=samplingPeriod,
                             init_gpa=init_gpa,
                             gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
        samplingPeriod = expt.get_rx_ts()[0]
        BW = 1 / samplingPeriod / hw.oversamplingFactor
        acqTime = nPoints[0] / BW  # us
        createSequence()

    # Plot sequence:
    expt.plot_sequence()

    # Run the experiment
    dataFull = []
    dummyData = []
    overData = []
    for ii in range(nScans):
        print("Scan %s ..." % (ii + 1))
        if not demo:
            rxd, msgs = expt.run()
            rxd['rx0'] = rxd[
                'rx0'] * 13.788  # Here I normalize to get the result in mV
        else:
            data, acqPoints = createSequenceDemo()
        # Get data
        if not demo:
            if dummyPulses > 0:
                dummyData = np.concatenate(
                    (dummyData,
                     rxd['rx0'][0:nRD * nPH * hw.oversamplingFactor]),
                    axis=0)
                overData = np.concatenate(
                    (overData,
                     rxd['rx0'][nRD * nPH * hw.oversamplingFactor::]),
                    axis=0)
            else:
                overData = np.concatenate((overData, rxd['rx0']), axis=0)
        else:
            if dummyPulses > 0:
                dummyData = np.concatenate(
                    (dummyData, data[0:nRD * nPH * hw.oversamplingFactor]),
                    axis=0)
                overData = np.concatenate(
                    (overData, data[nRD * nPH * hw.oversamplingFactor::]),
                    axis=0)
            else:
                overData = np.concatenate((overData, data), axis=0)
    if not demo: expt.__del__()
    print('Scans done!')
    rawData['overData'] = overData

    # Fix the echo position using oversampled data
    if dummyPulses > 0:
        dummyData = np.reshape(dummyData,
                               (nScans, nPH, nRD * hw.oversamplingFactor))
        dummyData = np.average(dummyData, axis=0)
        rawData['dummyData'] = dummyData
        overData = np.reshape(overData,
                              (nScans, 1, nPH, nRD * hw.oversamplingFactor))
        for ii in range(nScans):
            overData[ii, :, :, :] = mri.fixEchoPosition(
                dummyData, overData[ii, :, :, :])

    # Generate dataFull
    overData = np.squeeze(
        np.reshape(overData, (1, nRD * hw.oversamplingFactor * nPH * nScans)))
    dataFull = sig.decimate(overData,
                            hw.oversamplingFactor,
                            ftype='fir',
                            zero_phase=True)

    # Get index for krd = 0
    # Average data
    dataProv = np.reshape(dataFull, (nScans, nRD * nPH))
    dataProv = np.average(dataProv, axis=0)
    # Reorganize the data acording to sweep mode
    dataProv = np.reshape(dataProv, (nPH, nRD))
    dataTemp = dataProv * 0
    for ii in range(nPH):
        dataTemp[ind[ii], :] = dataProv[ii, :]
    dataProv = dataTemp
    # Check where is krd = 0
    dataProv = dataProv[int(nPoints[1] / 2), :]
    indkrd0 = np.argmax(np.abs(dataProv))
    if indkrd0 < nRD / 2 - addRdPoints or indkrd0 > nRD / 2 + addRdPoints:
        indkrd0 = int(nRD / 2)

    # Get individual images
    dataFull = np.reshape(dataFull, (nScans, nPH, nRD))
    dataFull = dataFull[:, :, indkrd0 - int(nPoints[0] / 2):indkrd0 +
                        int(nPoints[0] / 2)]
    dataTemp = dataFull * 0
    for ii in range(nPH):
        dataTemp[:, ind[ii], :] = dataFull[:, ii, :]
    dataFull = dataTemp
    imgFull = dataFull * 0
    for ii in range(nScans):
        imgFull[ii, :, :] = np.fft.ifftshift(
            np.fft.ifftn(np.fft.ifftshift(dataFull[ii, :, :])))
    rawData['dataFull'] = dataFull
    rawData['imgFull'] = imgFull

    # Average data
    data = np.average(dataFull, axis=0)
    data = np.reshape(data, (nPH, nPoints[0]))

    # Do zero padding
    dataTemp = np.zeros((nPoints[1], nPoints[0]))
    dataTemp = dataTemp + 1j * dataTemp
    dataTemp[0:nPH, :] = data
    data = np.reshape(dataTemp, (1, nPoints[0] * nPoints[1]))

    # Fix the position of the sample according to dfov
    kMax = np.array(nPoints) / (2 * np.array(fov)) * np.array(axesEnable)
    kRD = np.linspace(-kMax[0], kMax[0], num=nPoints[0], endpoint=False)
    kPH = np.linspace(-kMax[1], kMax[1], num=nPoints[1], endpoint=False)
    kPH, kRD = np.meshgrid(kPH, kRD)
    kRD = np.reshape(kRD, (1, nPoints[0] * nPoints[1]))
    kPH = np.reshape(kPH, (1, nPoints[0] * nPoints[1]))
    dPhase = np.exp(-2 * np.pi * 1j * (dfov[0] * kRD + dfov[1] * kPH))
    data = np.reshape(data * dPhase, (nPoints[1], nPoints[0]))
    rawData['kSpace3D'] = data
    img = np.fft.ifftshift(np.fft.ifftn(np.fft.ifftshift(data)))
    rawData['image3D'] = img
    data = np.reshape(data, (1, nPoints[0] * nPoints[1]))

    # Create sampled data
    kRD = np.reshape(kRD, (nPoints[0] * nPoints[1], 1))
    kPH = np.reshape(kPH, (nPoints[0] * nPoints[1], 1))
    data = np.reshape(data, (nPoints[0] * nPoints[1], 1))
    rawData['kMax'] = kMax
    rawData['sampled'] = np.concatenate((kRD, kPH, data), axis=1)
    data = np.reshape(data, (nPoints[1], nPoints[0]))

    # Save data
    mri.saveRawData(rawData)

    # Plot data for 1D case
    if (nPH == 1):
        # Plot k-space
        plt.figure(3)
        dataPlot = data[0, :]
        plt.subplot(1, 2, 1)
        if axesEnable[0] == 0:
            tVector = np.linspace(
                -acqTime / 2, acqTime / 2, num=nPoints[0],
                endpoint=False) * 1e-3
            sMax = np.max(np.abs(dataPlot))
            indMax = np.argmax(np.abs(dataPlot))
            timeMax = tVector[indMax]
            sMax3 = sMax / 3
            dataPlot3 = np.abs(np.abs(dataPlot) - sMax3)
            indMin = np.argmin(dataPlot3)
            timeMin = tVector[indMin]
            T2 = np.abs(timeMax - timeMin)
            plt.plot(tVector, np.abs(dataPlot))
            plt.plot(tVector, np.real(dataPlot))
            plt.plot(tVector, np.imag(dataPlot))
            plt.xlabel('t (ms)')
            plt.ylabel('Signal (mV)')
            print("T2 = %s us" % (T2))
        else:
            plt.plot(kRD[:, 0], np.abs(dataPlot))
            plt.yscale('log')
            plt.xlabel('krd (mm^-1)')
            plt.ylabel('Signal (mV)')
            echoTime = np.argmax(np.abs(dataPlot))
            echoTime = kRD[echoTime, 0]
            print("Echo position = %s mm^{-1}" % round(echoTime, 1))
        # Plot image
        plt.subplot(122)
        img = img[0, :]
        if axesEnable[0] == 0:
            xAxis = np.linspace(
                -BW / 2, BW / 2, num=nPoints[0], endpoint=False) * 1e3
            plt.plot(xAxis, np.abs(img), '.')
            plt.xlabel('Frequency (kHz)')
            plt.ylabel('Density (a.u.)')
            print("Smax = %s mV" % (np.max(np.abs(img))))
        else:
            xAxis = np.linspace(-fov[0] / 2 * 1e2,
                                fov[0] / 2 * 1e2,
                                num=nPoints[0],
                                endpoint=False)
            plt.plot(xAxis, np.abs(img))
            plt.xlabel('Position RD (cm)')
            plt.ylabel('Density (a.u.)')

    # Plot data for 2D case
    else:
        # Plot k-space
        plt.figure(3)
        dataPlot = data
        plt.subplot(131)
        plt.imshow(np.log(np.abs(dataPlot)), cmap='gray')
        plt.axis('off')
        # Plot image
        if sweepMode == 3:
            imgPlot = img[round(nPH / 4):round(3 * nPH / 4), :]
        else:
            imgPlot = img
        plt.subplot(132)
        plt.imshow(np.abs(imgPlot), cmap='gray')
        plt.axis('off')
        plt.title(rawData['fileName'])
        plt.subplot(133)
        plt.imshow(np.angle(imgPlot), cmap='gray')
        plt.axis('off')

    plt.figure(5)
    plt.subplot(121)
    data1d = data[:, int(nPoints[0] / 2)]
    plt.plot(abs(data1d))
    plt.subplot(122)
    img1d = img[:, int(nPoints[0] / 2)]
    plt.plot(np.abs(img1d) * 1e3)

    plt.show()
Пример #29
0
def rabiflopStandalone(
    init_gpa= False,                 
    larmorFreq = 3.0806, # MHz
    rfExAmp = 0.4, # a.u.
    rfReAmp = 0.8, # a.u.
    rfExTime = 22, # us
    rfReTime = 22, # us 
    nPoints = 100,
    acqTime = 18, # ms
    echoTime = 20, # ms
    repetitionTime = 1000, # ms
    plotSeq = 0, # 0 to run sequence, 1 to plot sequence
    pulseShape = 'Rec',  # 'Rec' for square pulse shape, 'Sinc' for sinc pulse shape
    shimming0 = [-77.5, -70, 7.5], 
    nShimming = 10, # number of samples to sweep in each gradient direction
    dShimming = [2.5, 2.5, 2.5] # shimming step in each direction
    ):
    
    freqCal = 0
    plt.ion()

    # Miscellaneous
    deadTime = 400 # us, time between excitation and first acquisition
    shimming0 = np.array(shimming0)*1e-4
    
    # Varibales to fundamental units
    larmorFreq *= 1e6
    rfExTime *= 1e-6
    rfReTime *= 1e-6
    acqTime *= 1e-3
    echoTime *= 1e-3
    repetitionTime *= 1e-3
    
    # Inputs for rawData
    rawData={}
    rawData['seqName'] = 'ShimmingCal'
    rawData['larmorFreq'] = larmorFreq      # Larmor frequency
    rawData['rfExAmp'] = rfExAmp             # rf excitation pulse amplitude
    rawData['rfReAmp'] = rfReAmp
    rawData['rfExTime'] = rfExTime
    rawData['rfReTime'] = rfReTime
    rawData['nPoints'] = nPoints
    rawData['acqTime'] = acqTime
    rawData['echoTime'] = echoTime
    rawData['repetitionTime'] = repetitionTime
    rawData['pulseShape'] = pulseShape
    rawData['deadTime'] = deadTime*1e-6
    rawData['shimming0'] = shimming0
    rawData['nShimming'] = nShimming
    rawData['dShimming'] = dShimming
    rawData['shimming'] = shimming0
    rawData['addRdPoints'] = 10
    
    # Shimming vectors
    dsx = nShimming*dShimming[0]*1e-4
    dsy = nShimming*dShimming[1]*1e-4
    dsz = nShimming*dShimming[2]*1e-4
    sxVector = np.linspace(shimming0[0]-dsx/2, shimming0[0]+dsx/2, num=nShimming, endpoint=False)
    syVector = np.linspace(shimming0[1]-dsy/2, shimming0[1]+dsy/2, num=nShimming, endpoint=False)
    szVector = np.linspace(shimming0[2]-dsz/2, shimming0[2]+dsz/2, num=nShimming, endpoint=False)
    
    # Bandwidth 
    bw = nPoints/acqTime*1e-6 # MHz
    bwov = bw*hw.oversamplingFactor # MHz
    samplingPeriod = 1/bwov # us
    rawData['bw'] = bw
    rawData['samplingPeriod'] = samplingPeriod
    fVector = np.linspace(-bw/2, bw/2, num=nPoints, endpoint=False)
    
    # Time variables in us and MHz
    larmorFreq *=1e-6
    rfExTime *=1e6
    rfReTime *=1e6
    echoTime *=1e6
    repetitionTime *=1e6
    acqTime *=1e6
    
    #  SEQUENCE  ############################################################################################
    def createSequence(shimming):
        # Set shimming
        mri.iniSequence(expt, 20, shimming)
        
        # Initialize time
        tEx = 20e3
            
        # Excitation pulse
        t0 = tEx-hw.blkTime-rfExTime/2
        if pulseShape=='Rec':
            mri.rfRecPulse(expt, t0, rfExTime, rfExAmp, 0)
        elif pulseShape=='Sinc':
            mri.rfSincPulse(expt, t0, rfExTime, 7, rfExAmp, 0)
        
        # Refocusing pulse
        t0 = tEx+echoTime/2-rfReTime/2-hw.blkTime
        if pulseShape=='Rec':
            mri.rfRecPulse(expt, t0, rfReTime, rfReAmp, np.pi/2)
        elif pulseShape=='Sinc':
            mri.rfSincPulse(expt, t0, rfReTime, 7, rfReAmp, np.pi/2)
        
        # Acquisition window
        t0 = tEx+echoTime-acqTime/2
        mri.rxGate(expt, t0, acqTime)
        
        # End sequence
        mri.endSequence(expt, repetitionTime)
        
        
    
    # Calibrate frequency
    if freqCal==1: 
        mri.freqCalibration(rawData, bw=0.05)
        mri.freqCalibration(rawData, bw=0.005)
        larmorFreq = rawData['larmorFreq']*1e-6
        
    # INIT EXPERIMENT
    dataAll = []
    gx = []
    gy = []
    gz = []
    ppmx = []
    ppmy = []
    ppmz = []
    
    # shimming for Gx
    for sx in sxVector:
        shimming = np.array([sx, shimming0[1], shimming0[2]])
        expt = ex.Experiment(lo_freq=larmorFreq, rx_t=samplingPeriod, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
        samplingPeriod = expt.get_rx_ts()[0]
        bw = 1/samplingPeriod/hw.oversamplingFactor
        acqTime = nPoints/bw
        rawData['bw'] = bw
        createSequence(shimming)
        if plotSeq==1:
            expt.plot_sequence()
            plt.show(block=False)
            expt.__del__()
        elif plotSeq==0:
            print(shimming*1e4,  '.- Running...')
            rxd, msgs = expt.run()
            expt.__del__()
            data = sig.decimate(rxd['rx0']*13.788, hw.oversamplingFactor, ftype='fir', zero_phase=True)
            fwhm, max = getPeakProperties(fVector, data)
            gx = np.concatenate((gx, np.array([max])), axis=0)
            ppmx = np.concatenate((ppmx, np.array([fwhm/larmorFreq*1e6])), axis=0)
            dataAll = np.concatenate((dataAll, data), axis=0)
            # Plots
            plt.figure(1)
            plt.plot(sx*1e4, max, 'b.')
            plt.figure(2)
            plt.plot(sx*1e4, fwhm/larmorFreq*1e6, 'b.')
            plt.show(block=False)
            plt.pause(0.05)
    idx = np.argmax(gx)
    sxOpt = sxVector[idx]
    
    # shimming for Gy
    for sy in syVector:
        shimming = np.array([sxOpt, sy, shimming0[2]])
        expt = ex.Experiment(lo_freq=larmorFreq, rx_t=samplingPeriod, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
        samplingPeriod = expt.get_rx_ts()[0]
        bw = 1/samplingPeriod/hw.oversamplingFactor
        acqTime = nPoints/bw
        rawData['bw'] = bw
        createSequence(shimming)
        if plotSeq==1:
            expt.plot_sequence()
            plt.show(block=False)
            expt.__del__()
        elif plotSeq==0:
            print(shimming*1e4,  '.- Running...')
            rxd, msgs = expt.run()
            expt.__del__()
            data = sig.decimate(rxd['rx0']*13.788, hw.oversamplingFactor, ftype='fir', zero_phase=True)
            fwhm, max = getPeakProperties(fVector, data)
            gy = np.concatenate((gy, np.array([max])), axis=0)
            ppmy = np.concatenate((ppmy, np.array([fwhm/larmorFreq*1e6])), axis=0)
            dataAll = np.concatenate((dataAll, data), axis=0)
            plt.figure(1)
            plt.plot(sy*1e4, max, 'g.')
            plt.figure(2)
            plt.plot(sy*1e4, fwhm/larmorFreq*1e6, 'g.')
            plt.show(block=False)
            plt.pause(0.05)
    idx = np.argmax(gy)
    syOpt = syVector[idx]
    
    # shimming for Gz
    for sz in szVector:
        shimming = np.array([sxOpt, syOpt, sz])
        expt = ex.Experiment(lo_freq=larmorFreq, rx_t=samplingPeriod, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
        samplingPeriod = expt.get_rx_ts()[0]
        bw = 1/samplingPeriod/hw.oversamplingFactor
        acqTime = nPoints/bw
        rawData['bw'] = bw
        createSequence(shimming)
        if plotSeq==1:
            expt.plot_sequence()
            plt.show(block=False)
            expt.__del__()
        elif plotSeq==0:
            print(shimming*1e4,  '.- Running...')
            rxd, msgs = expt.run()
            expt.__del__()
            data = sig.decimate(rxd['rx0']*13.788, hw.oversamplingFactor, ftype='fir', zero_phase=True)
            fwhm, max = getPeakProperties(fVector, data)
            gz = np.concatenate((gz, np.array([max])), axis=0)
            ppmz = np.concatenate((ppmz, np.array([fwhm/larmorFreq*1e6])), axis=0)
            dataAll = np.concatenate((dataAll, data), axis=0)
            plt.figure(1)
            plt.plot(sz*1e4, max, 'r.')
            plt.figure(2)
            plt.plot(sz*1e4, fwhm/larmorFreq*1e6, 'r.')
            plt.show(block=False)
            plt.pause(0.05)
    idx = np.argmax(gz)
    szOpt = szVector[idx]
    rawData['shimming'] = np.array([sxOpt, syOpt, szOpt])
    
    # Get the values for the optimal case
    shimming = np.array([sxOpt, syOpt, szOpt])
#    expt = ex.Experiment(lo_freq=larmorFreq, rx_t=samplingPeriod, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
#    samplingPeriod = expt.get_rx_ts()[0]
#    bw = 1/samplingPeriod/hw.oversamplingFactor
#    acqTime = nPoints/bw
#    rawData['bw'] = bw
#    createSequence(shimming)
#    if plotSeq==1:
#        expt.plot_sequence()
#        plt.show(block=False)
#        expt.__del__()
#    elif plotSeq==0:
#        print(shimming*1e4,  '.- Running...')
#        rxd, msgs = expt.run()
#        expt.__del__()
#        data = sig.decimate(rxd['rx0']*13.788, hw.oversamplingFactor, ftype='fir', zero_phase=True)
#        fwhm, max = getPeakProperties(fVector, data)
#        plt.figure(1)
#        plt.plot(0, max, 'k.')
#        plt.figure(2)
#        plt.plot(0, fwhm/larmorFreq*1e6, 'k.')
#        plt.show(block=False)
#        plt.pause(0.05)

    # Save data
    mri.saveRawData(rawData)
    plt.figure(3)
    plt.plot(sxVector*1e4, gx, 'b.', 
        syVector*1e4, gy, 'g.', 
        szVector*1e4, gz, 'r.')
    plt.title(rawData['fileName'])
    plt.xlabel('Shimming (a.u.)')
    plt.ylabel('FFT peak amplitude (a.u.)')
    plt.legend(['x Axis', 'y Axis', 'z Axis'])
    
    plt.figure(4)
    plt.plot(sxVector*1e4, ppmx, 'b.', 
        syVector*1e4, ppmy, 'g.', 
        szVector*1e4, ppmz, 'r.')
    plt.title(rawData['fileName'])
    plt.xlabel('Shimming (a.u.)')
    plt.ylabel('Homogeneity (ppm)')
    plt.legend(['x Axis', 'y Axis', 'z Axis'])
    
    print('Best shimming = ', shimming*1e4)
    
    plt.show(block=True)
Пример #30
0
def turbo_spin_echo(self, plotSeq):

    init_gpa = True
    lo_freq = self.lo_freq
    rf_amp = self.rf_amp
    #    trs=self.trs
    rf_pi_duration = None
    rf_pi2_duration = self.rf_pi2_duration
    echo_duration = self.echo_duration * 1e3
    tr_duration = self.tr_duration * 1e3
    BW = self.BW
    shim_x: float = self.shim[0]
    shim_y: float = self.shim[1]
    shim_z: float = self.shim[2]
    nScans = self.nScans
    fov_x: int = self.fov_rd * 1e-2
    fov_y: int = self.fov_ph * 1e-2
    fov_z: int = self.fov_sl * 1e-2
    trap_ramp_duration = self.trap_ramp_duration
    phase_grad_duration = self.phase_grad_duration
    echos_per_tr = self.echos_per_tr
    rd_preemph_factor: float = self.preemph_factor
    sweep_mode = self.sweep_mode
    par_acq_factor = self.par_acq_factor
    n_rd = self.n_rd
    n_ph = self.n_ph
    n_sl = self.n_sl
    x = self.x
    y = self.y
    z = self.z
    oversampling_factor = self.oversampling_factor

    BW = BW * 1e-3
    #    trap_ramp_pts=np.int32(trap_ramp_duration*0.2)    # 0.2 puntos/ms
    trap_ramp_pts = 10
    grad_readout_delay = 9  #8.83    # readout amplifier delay
    grad_phase_delay = 9  #8.83
    grad_slice_delay = 9  #8.83
    rx_period = 1 / (BW * oversampling_factor)
    """
    readout gradient: x
    phase gradient: y
    slice/partition gradient: z
    """

    expt = ex.Experiment(lo_freq=lo_freq,
                         rx_t=rx_period,
                         init_gpa=init_gpa,
                         gpa_fhdo_offset_time=(1 / 0.2 / 3.1))
    true_rx_period = expt.get_rx_ts()[0]
    true_BW = 1 / true_rx_period
    true_BW = true_BW / oversampling_factor
    readout_duration = n_rd / true_BW

    # We calculate here the realtive sequence efficiency
    alphaRO = fov_x / n_rd * np.sqrt(np.float(n_rd) / true_BW)
    alphaPH = fov_y / n_ph * np.sqrt(np.float(echos_per_tr))
    alphaSL = fov_z / n_sl * np.sqrt(
        np.float(n_sl) / (np.float(n_sl) / 2 + np.float(par_acq_factor)))
    alpha = alphaRO * alphaPH * alphaSL * 10000
    print('alpha:%f' % (alpha))

    if rf_pi_duration is None:
        rf_pi_duration = 2 * rf_pi2_duration

    # Calibration constans to change from T/m to DAC amplitude

    gammaB = 42.56e6  # Gyromagnetic ratio in Hz/T
    # Get readout, phase and slice amplitudes
    # Readout gradient amplitude
    Grd = true_BW * 1e6 / (gammaB * fov_x)
    # Phase gradient amplitude
    if (n_ph == 1):
        Gph = 0
    else:
        Gph = n_ph / (2 * gammaB * fov_y * phase_grad_duration * 1e-6)
    # Slice gradient amplitude
    if (n_sl == 1):
        Gsl = 0
    else:
        Gsl = n_sl / (2 * gammaB * fov_z * phase_grad_duration * 1e-6)

    # Get the phase gradient vector
    if (n_ph > 1):
        phase_amps = np.linspace(-Gph, Gph, n_ph)
    else:
        phase_amps = np.linspace(-Gph, Gph, n_ph)
    ind = getIndex(self, phase_amps, echos_per_tr, n_ph, sweep_mode)
    phase_amps = phase_amps[ind]

    # Get the slice gradient vector
    if (n_sl > 1):
        slice_amps = np.linspce(-Gsl, Gsl, n_sl + 1)
        slice_amps = slice_amps[1:n_sl + 1]
    else:
        slice_amps = np.linspace(-Gsl, Gsl, n_sl)

#*********************************************************************************
#*********************************************************************************
#*********************************************************************************

    def rf_wf(tstart, echo_idx):
        pi2_phase = 1  # x
        pi_phase = 1j  # y
        if echo_idx == 0:
            # do pi/2 pulse, then start first pi pulse
            return np.array([
                tstart + (echo_duration - rf_pi2_duration) / 2,
                tstart + (echo_duration + rf_pi2_duration) / 2,
                tstart + echo_duration - rf_pi_duration / 2
            ]), np.array([pi2_phase * rf_amp, 0, pi_phase * rf_amp])
#        elif echo_idx == self.echos_per_tr and ph==n_ph and sl==n_sl-1:
#            # last echo of the full sequence
#            return np.array([tstart + rf_pi_duration/2, tr_duration-echo_duration*echos_per_tr]), np.array([0, 0])
        elif echo_idx == self.echos_per_tr:
            # last echo on any other echo train
            return np.array([tstart + rf_pi_duration / 2]), np.array([0])
        else:
            # finish last pi pulse, start next pi pulse
            return np.array([
                tstart + rf_pi_duration / 2,
                tstart + echo_duration - rf_pi_duration / 2
            ]), np.array([0, pi_phase * self.rf_amp])

#*********************************************************************************
#*********************************************************************************
#*********************************************************************************

    def tx_gate_wf(tstart, echo_idx, ph, sl):
        tx_gate_pre = 15  # us, time to start the TX gate before each RF pulse begins
        tx_gate_post = 1  # us, time to keep the TX gate on after an RF pulse ends

        if echo_idx == 0:
            # do pi/2 pulse, then start first pi pulse
            return np.array([tstart + (echo_duration - rf_pi2_duration)/2 - tx_gate_pre,
                             tstart + (echo_duration + rf_pi2_duration)/2 + tx_gate_post,
                             tstart + echo_duration - rf_pi_duration/2 - tx_gate_pre]), \
                             np.array([1, 0, 1])
        elif echo_idx == self.echos_per_tr and ph == n_ph and sl == n_sl - 1:
            return np.array([
                tstart + rf_pi_duration / 2 + tx_gate_post,
                tstart + tr_duration - echo_duration * echos_per_tr
            ]), np.array([0, 0])
        elif echo_idx == echos_per_tr:
            # finish final RF pulse
            return np.array([tstart + rf_pi_duration / 2 + tx_gate_post
                             ]), np.array([0])
        else:
            # finish last pi pulse, start next pi pulse
            return np.array([tstart + rf_pi_duration/2 + tx_gate_post, tstart + self.echo_duration - rf_pi_duration/2 - tx_gate_pre]), \
                np.array([0, 1])

#*********************************************************************************
#*********************************************************************************
#*********************************************************************************

    def readout_wf(tstart, echo_idx):
        if echo_idx == 0:
            return np.array([tstart]), np.array([0])  # keep on zero otherwise
#        elif echo_idx==echos_per_tr:
#            return np.array([tstart + (echo_duration - readout_duration)/2, tstart + (echo_duration + readout_duration)/2, tstart+echo_duration+tr_duration-echos_per_tr*echo_duration ]), np.array([1, 0, 0])
        else:
            return np.array([
                tstart + (echo_duration - readout_duration) / 2,
                tstart + (echo_duration + readout_duration) / 2
            ]), np.array([1, 0])

#*********************************************************************************
#*********************************************************************************
#*********************************************************************************

    def readout_grad_wf(tstart, echo_idx):
        if echo_idx == 0:
            #            return trap_cent(tstart+echo_duration/2+rf_pi2_duration/2+trap_ramp_duration+readout_duration/2-grad_readout_delay, Grd/2*rd_preemph_factor, readout_duration+trap_ramp_duration,
            #                             trap_ramp_duration, trap_ramp_pts)
            return rect_cent(
                tstart + echo_duration / 2 + rf_pi2_duration / 2 +
                trap_ramp_duration + readout_duration / 2 - grad_readout_delay,
                Grd / 2.0 * rd_preemph_factor, readout_duration,
                trap_ramp_duration)
        else:
            #            return trap_cent(tstart + echo_duration/2-grad_readout_delay, Grd, readout_duration+trap_ramp_duration,
            #                             trap_ramp_duration, trap_ramp_pts)
            return rect_cent(tstart + echo_duration / 2 - grad_readout_delay,
                             Grd, readout_duration, trap_ramp_duration)

#*********************************************************************************
#*********************************************************************************
#*********************************************************************************

    def phase_grad_wf(tstart, echo_idx, ph):
        #        t1, a1 = trap_cent(tstart + (rf_pi_duration+phase_grad_duration-trap_ramp_duration)/2+trap_ramp_duration-grad_phase_delay,
        #                            phase_amps[ph-1], phase_grad_duration, trap_ramp_duration, trap_ramp_pts)
        #        t2, a2 = trap_cent(tstart + echo_duration/2 + readout_duration/2+phase_grad_duration/2+trap_ramp_duration/2-grad_phase_delay,
        #                            -phase_amps[ph-1], phase_grad_duration, trap_ramp_duration, trap_ramp_pts)
        t1, a1 = rect_cent(
            tstart + rf_pi_duration / 2 + phase_grad_duration / 2 +
            trap_ramp_duration - grad_phase_delay, phase_amps[ph - 1],
            phase_grad_duration, trap_ramp_duration)
        t2, a2 = rect_cent(
            tstart + echo_duration / 2 + readout_duration / 2 +
            trap_ramp_duration + phase_grad_duration / 2 - grad_phase_delay,
            -phase_amps[ph - 1], phase_grad_duration, trap_ramp_duration)
        if echo_idx == 0:
            return np.array([tstart]), np.array([0])  # keep on zero otherwise
        elif echo_idx == echos_per_tr:  # last echo, don't need 2nd trapezoids
            return t1, a1
        else:  # otherwise do both trapezoids
            return np.hstack([t1, t2]), np.hstack([a1, a2])

#*********************************************************************************
#*********************************************************************************
#*********************************************************************************

    def slice_grad_wf(tstart, echo_idx, sl):
        #        t1, a1 = trap_cent(tstart + (rf_pi_duration+phase_grad_duration-trap_ramp_duration)/2+trap_ramp_duration-grad_phase_delay, slice_amps[sl], phase_grad_duration,
        #                           trap_ramp_duration, trap_ramp_pts)
        #        t2, a2 = trap_cent(tstart +echo_duration/2 + readout_duration/2+phase_grad_duration/2+trap_ramp_duration/2-grad_slice_delay, -slice_amps[sl], phase_grad_duration,
        #                           trap_ramp_duration, trap_ramp_pts)
        t1, a1 = rect_cent(
            tstart + rf_pi_duration / 2 + trap_ramp_duration +
            phase_grad_duration / 2 - grad_slice_delay, slice_amps[sl],
            phase_grad_duration, trap_ramp_duration)
        t2, a2 = rect_cent(
            tstart + echo_duration / 2 + readout_duration / 2 +
            trap_ramp_duration + phase_grad_duration / 2 - grad_slice_delay,
            -slice_amps[sl], phase_grad_duration, trap_ramp_duration)
        if echo_idx == 0:
            return np.array([tstart]), np.array([0])  # keep on zero otherwise
        elif echo_idx == echos_per_tr:  # last echo, don't need 2nd trapezoids
            return t1, a1
        else:  # otherwise do both trapezoids
            return np.hstack([t1, t2]), np.hstack([a1, a2])

#*********************************************************************************
#*********************************************************************************
#*********************************************************************************

    global_t = 20  # start the first TR at 20us
    #    for nS in range(nScans):
    if par_acq_factor == 0:
        n_sl_par = n_sl
    else:
        n_sl_par = np.int32(n_sl / 2) + par_acq_factor
    for sl in range(n_sl_par):
        for ph_block in range(np.int32(n_ph / echos_per_tr)):
            for echo_idx in range(1 + echos_per_tr):
                tx_t, tx_a = rf_wf(global_t, echo_idx)
                tx_gate_t, tx_gate_a = tx_gate_wf(
                    global_t, echo_idx, ph_block * echos_per_tr + echo_idx, sl)
                readout_t, readout_a = readout_wf(global_t, echo_idx)
                rx_gate_t, rx_gate_a = readout_wf(global_t, echo_idx)
                readout_grad_t, readout_grad_a = readout_grad_wf(
                    global_t, echo_idx)
                phase_grad_t, phase_grad_a = phase_grad_wf(
                    global_t, echo_idx, ph_block * echos_per_tr + echo_idx)
                slice_grad_t, slice_grad_a = slice_grad_wf(
                    global_t, echo_idx, sl)

                expt.add_flodict({
                    'tx0': (tx_t, tx_a),
                    'grad_vx':
                    (eval('%s_grad_t' % (x)),
                     eval('%s_grad_a/(Gx_factor/1000)/10+shim_x' % (x))),
                    'grad_vy':
                    (eval('%s_grad_t' % (y)),
                     eval('%s_grad_a/(Gy_factor/1000)/10+shim_y' % (y))),
                    'grad_vz':
                    (eval('%s_grad_t' % (z)),
                     eval('%s_grad_a/(Gz_factor/1000)/10+shim_z' % (z))),
                    'rx0_en': (readout_t, readout_a),
                    'tx_gate': (tx_gate_t, tx_gate_a),
                    'rx_gate': (rx_gate_t, rx_gate_a),
                })

                global_t += echo_duration

            global_t += tr_duration - echo_duration * echos_per_tr

    expt.add_flodict({
        'grad_vx': (np.array([global_t + echo_duration]), np.array([0])),
        'grad_vy': (np.array([global_t + echo_duration]), np.array([0])),
        'grad_vz': (np.array([global_t + echo_duration]), np.array([0])),
    })

    if plotSeq == 1:  # What is the meaning of plotSeq??
        expt.plot_sequence()
        plt.show()
        expt.__del__()
    elif plotSeq == 0:
        for nS in range(nScans):
            print('nScan=%s' % (nS))
            rxd, msgs = expt.run()
            #            data_nodecimate = rxd['rx0']
            #Decimate
            rxd['rx0'] = sig.decimate(rxd['rx0'],
                                      oversampling_factor,
                                      ftype='fir',
                                      zero_phase=True)
            rxd['rx0'] = rxd[
                'rx0'] * 13.788  # Here I normalize to get the result in mV
            if nS == 0:
                n_rxd = rxd['rx0']
#                n_nodecimate = data_nodecimate
            else:
                n_rxd = np.concatenate((n_rxd, rxd['rx0']), axis=0)
#                n_nodecimate=np.concatenate((n_nodecimate, data_nodecimate), axis=0)
        if par_acq_factor == 0 and nScans > 1:
            n_rxd = np.reshape(n_rxd, (nScans, n_sl * n_ph * n_rd))
            data_avg = np.average(n_rxd, axis=0)
#            n_nodecimate=np.reshape(n_nodecimate, (nScans, n_sl*n_ph*n_rd))
#            data_nodecimate = np.average(n_nodecimate, axis=0)
        elif par_acq_factor > 0 and nScans > 1:
            n_rxd = np.reshape(n_rxd, (nScans, n_sl_par * n_ph * n_rd))
            data_avg = np.average(n_rxd, axis=0)
#            n_nodecimate=np.reshape(n_nodecimate, (nScans, n_sl_par*n_ph*n_rd))
#            data_nodecimate = np.average(n_nodecimate, axis=0)
        else:
            data_avg = n_rxd

        expt.__del__()

        # Reorganize the data matrix according to the sweep mode
        rxd_temp1 = np.reshape(data_avg, (n_sl_par, n_ph, n_rd))
        rxd_temp2 = rxd_temp1 * 0
        for ii in range(n_ph):
            ind_temp = ind[ii]
            rxd_temp2[:, ind_temp, :] = rxd_temp1[:, ii, :]

        rxd_temp3: complex = np.zeros((n_sl, n_ph, n_rd)) + 1j * np.zeros(
            (n_sl, n_ph, n_rd))
        rxd_temp3[0:n_sl_par, :, :] = rxd_temp2
        data_avg = np.reshape(rxd_temp3, -1)  # -1 means reshape to 1D array

        return n_rxd, msgs, data_avg