Exemple #1
0
 def gen_kspace(self,imouse=0):
     rcvrelems = nonzero(self.inputAcq.rcvrmouse_mapping==imouse)[0]
     if (len(rcvrelems)==0):
         print("Requested reconstruction for mouse %d, which is not in receiver map"%imouse, self.inputAcq.rcvrmouse_mapping)
         raise SystemExit
     nreps = rgf.get_dict_value(self.inputAcq.method_param_dict,"PVM_NRepetitions",1)
     self.kspace = empty([len(rcvrelems),nreps*self.inputAcq.ni*self.inputAcq.nfid,self.inputAcq.nf,self.inputAcq.nro],complex)
     for j,ircvr in enumerate(rcvrelems):
         self.kspace[j] = rgf.gen_kspace_simple(self.inputAcq,ircvr)
     self.kspace.shape = tuple([x for x in self.kspace.shape if x>1])
     if self.options.cen_out_pe1:
         self.kspace=rgf.centre_out_reordering(self.kspace,-2)
     if self.options.cen_out_pe2:
         self.kspace=rgf.centre_out_reordering(self.kspace,-3)
     if self.options.petable_pe1:
         self.kspace = rgf.petable_reordering(self.kspace,axis=-2,petable_array='t1',petable_name=self.petable_name)
     if self.options.petable_pe2:
         self.kspace = rgf.petable_reordering(self.kspace,axis=-3,petable_array='t2',petable_name=self.petable_name)
     if self.options.petable_ordered_pairs:
         self.kspace = rgf.petable_orderedpair_reordering(self.kspace,petable_arrays=('t1','t2'),petable_name=self.petable_name,\
                                                       matrix=(self.inputAcq.npe,self.inputAcq.npe2))
     self.kspace = rgf.fov_adjustment(self.kspace,self.options,self.inputAcq,imouse)
     if ((self.inputAcq.platform=="Bruker") and (self.inputAcq.nD==2)):
         print("Reordering multislice experiment...")
         slice_order = rgf.get_dict_value(self.inputAcq.method_param_dict,"PVM_OjbOrderList",arange(self.inputAcq.nslices))
         self.kspace[...,:,:,:] = self.kspace[...,slice_order,:,:]
     if self.options.dcshiftcorr: #do we use this?
         self.kspace,dcoff = rgf.DCartcorr(self.kspace,self.param_dict)
     if self.options.fermi_ellipse:
         self.kspace = rgf.fermi_ellipse_filter(self.kspace)
     elif self.options.fermi_pecirc:
         self.kspace = rgf.fermi_pecircle_filter(self.kspace) 
Exemple #2
0
 def gen_kspace(self, imouse=0):
     rcvrelems = nonzero(self.inputAcq.rcvrmouse_mapping == imouse)[0]
     if (len(rcvrelems) == 0):
         print(
             "Requested reconstruction for mouse %d, which is not in receiver map"
             % imouse, self.inputAcq.rcvrmouse_mapping)
         raise SystemExit
     nTRs = len(parse_petable_file(self.petable_name, 't1'))
     self.inputAcq.nf = nTRs
     self.inputAcq.ni_perchan = 1
     nreps = rgf.get_dict_value(self.inputAcq.method_param_dict,
                                "PVM_NRepetitions", 1)
     self.kspace = empty([
         nreps,
         len(rcvrelems), self.inputAcq.ni_perchan, self.inputAcq.nf,
         self.inputAcq.nro
     ], complex)
     for j, ircvr in enumerate(rcvrelems):
         self.kspace[:, j, ...] = gen_kspace_local(self.inputAcq,
                                                   ircvr,
                                                   nTRs=nTRs)
     #self.kspace.shape = tuple([x for x in self.kspace.shape if x>1])
     if self.options.petable_ordered_pairs:
         self.kspace = rgf.petable_orderedpair_reordering(self.kspace,petable_arrays=('t1','t2'),petable_name=self.petable_name,\
                                                       matrix=(self.inputAcq.npe,self.inputAcq.npe2))
         print(self.kspace.shape)
     elif self.options.petable_pe1:
         self.kspace = rgf.petable_reordering(
             self.kspace,
             axis=-2,
             petable_array='t1',
             petable_name=self.petable_name)
     elif self.options.petable_pe2:
         self.kspace = rgf.petable_reordering(
             self.kspace,
             axis=-3,
             petable_array='t2',
             petable_name=self.petable_name)
     self.kspace = rgf.fov_adjustment(self.kspace, self.options,
                                      self.inputAcq, imouse)
     if (rgf.get_dict_value(self.inputAcq.method_param_dict, 'PVM_EncPft',
                            [1.0, 1.0, 1.0])[0] > 1.0005):
         #first: zero-pad k-space
         nrofull = rgf.get_dict_value(self.inputAcq.method_param_dict,
                                      'PVM_Matrix', [1, 1, 1])[0]
         nroacq = rgf.get_dict_value(self.inputAcq.method_param_dict,
                                     'PVM_EncMatrix', [1, 1, 1])[0]
         npad = nrofull - nroacq
         self.kspace = append(zeros(self.kspace.shape[0:-1] + (npad, ),
                                    complex),
                              self.kspace,
                              axis=-1)
         self.inputAcq.data_shape[-1] = nrofull
         self.Pftacq = True
     if self.options.fermi_ellipse:
         self.kspace = rgf.fermi_ellipse_filter(self.kspace)
Exemple #3
0
 def recon(self):
     if ((self.Pftacq == True) and (not self.options.nofft)):
         #recon centre of k-space (with apodization) and obtain normed conjugate
         print("Partial fourier recon in the read direction...")
         nrofull = rgf.get_dict_value(self.inputAcq.method_param_dict,
                                      'PVM_Matrix', [1, 1, 1])[0]
         nroacq = rgf.get_dict_value(self.inputAcq.method_param_dict,
                                     'PVM_EncMatrix', [1, 1, 1])[0]
         filt = 1.0 / (
             1.0 + exp(-(nroacq - arange(nrofull)) / self.options.apowidth))
         k_sym = self.kspace * filt
         img_sym = rgf.recon_3d(k_sym)
         del k_sym
         Pmult = exp(
             -1.j * angle(img_sym))  #conjugate(img_sym)/where(abs(img_sym))
         #multiply kspace by window function
         Kweight = 1.0/(1.0+exp((nrofull-nroacq-arange(nrofull))/self.options.apowidth))+ \
                   1.0/(1.0+exp((nroacq-arange(nrofull))/self.options.apowidth))
         weighted_image = rgf.recon_3d(self.kspace *
                                       Kweight).astype(complex)
         self.image_data = (weighted_image * Pmult).real
     else:
         rgf.default_recon(self)
     if ((self.options.complexavg) and (len(self.inputAcq.data_shape) > 4)):
         thresh = percentile(abs(self.image_data).flat, 75.0)
         nstep = 8
         g_coord = mgrid[0:self.image_data.shape[-3]:nstep,
                         0:self.image_data.shape[-2]:nstep,
                         0:self.image_data.shape[-1]:nstep]
         pts_log = (abs(self.image_data[0,0,ravel(g_coord[0]),ravel(g_coord[1]),ravel(g_coord[2])])>thresh)* \
                   (abs(self.image_data[0,1,ravel(g_coord[0]),ravel(g_coord[1]),ravel(g_coord[2])])>thresh)
         Ainds = reshape(g_coord, (3, len(pts_log)))[:, pts_log]
         Ivals1 = mean(self.image_data[:, 0, Ainds[0, :], Ainds[1, :],
                                       Ainds[2, :]],
                       axis=0)
         Ivals2 = mean(self.image_data[:, 1, Ainds[0, :], Ainds[1, :],
                                       Ainds[2, :]],
                       axis=0)
         Cvals = Ivals1 * conj(Ivals2)
         Elem_phase_diff = arctan2(Cvals.imag, Cvals.real)
         pfit = Phase_shift_cal(Elem_phase_diff, Ainds)
         fullphaseimg = fullphasemap(pfit, self.image_data.shape)
         self.image_data = self.image_data[:,
                                           0, :, :, :] + self.image_data[:,
                                                                         1, :, :, :] * exp(
                                                                             1.j
                                                                             *
                                                                             fullphaseimg
                                                                         )
         self.image_data.shape = (self.image_data.shape[0], 1,
                                  self.image_data.shape[-3],
                                  self.image_data.shape[-2],
                                  self.image_data.shape[-1])
     if (not self.options.outputreps):
         print("Averaging repetitions...")
         self.image_data = mean(abs(self.image_data), axis=0)
Exemple #4
0
def add_scanparams_to_mncheader(inputAcq, filename, imouse):
    print("Adding scan header to minc header...")
    nmice = inputAcq.nmice
    if (inputAcq.platform == "Varian"):
        dparamlist = [
            'sw', 'tr', 'np', 'nv', 'nv2', 'nv_lores', 'nv2_lores', 'ni', 'nf',
            'ne', 'etl', 'lro', 'lpe', 'lpe2', 'thk', 'ns', 'phi', 'psi',
            'theta', 'fn', 'fn1', 'fn2', 'nmice', 'arrayelements', 'arraydim',
            'nD', 'nleaf', 'nfid', 'npetables', 'frac_kx', 'esp', 'sfrq', 'te',
            'ti', 'nt', 'ngainlo', 'gainlo', 'gainhi', 'gain', 'pss', 'mm_pro',
            'mm_ppe', 'mm_ppe2', 'ppe', 'ppe2', 'pro'
        ]
        sparamlist = [
            'array', 'seqfil', 'pslabel', 'orient', 'rfcoil', 'time_submitted',
            'petable', 'rcvrs', 'seqcon', 'vrgain', 'acqtype', 'username',
            'datestr', 'mmconf', 'dp', 'console', 'console_rev', 'tn',
            'protocols'
        ]
        image_param = inputAcq.param_dict
        platform_str = "vnmr"
    elif (inputAcq.platform == "Bruker"):
        dparamlist = [
            'PVM_EchoTime', 'PVM_RepetitionTime', 'PVM_NAverages',
            'PVM_EffSWh', 'PVM_AcquisitionTime', 'PVM_SliceThick'
        ]
        sparamlist = [
            'Method', 'OWNER', 'PVM_ScanTimeStr', 'PVM_Matrix', 'PVM_Fov',
            'PVM_SPackArrSliceOrient', 'PVM_SPackArrReadOrient',
            'PVM_SPackArrReadOffset', 'PVM_SPackArrPhase1Offset',
            'PVM_SPackArrPhase2Offset', 'PVM_SPackArrSliceOffset',
            'PVM_SPackArrSliceGap', 'PVM_SPackArrSliceDistance'
        ]
        image_param = inputAcq.method_param_dict
        platform_str = "brkr"
    for ckey in dparamlist:
        cval = get_dict_value(image_param, ckey, 0.0)
        if (hasattr(cval, '__len__')):
            if ((len(cval) == nmice) or (ckey == "mm_ppe")
                    or (ckey == "mm_ppe2") or (ckey == "mm_pro")):
                cval = cval[imouse]
            else:
                cval = cval[0]
        cmdstr = 'minc_modify_header -dinsert %s:%s=%f %s > /dev/null' \
                 % (platform_str,ckey,cval,filename)
        os.system(cmdstr)
    cmdstr = 'minc_modify_header -dinsert %s:coil=%f %s > /dev/null' \
             % (platform_str,imouse+1,filename)
    os.system(cmdstr)
    for ckey in sparamlist:
        cval = str(get_dict_value(image_param, ckey, "NA"))
        cmdstr = 'minc_modify_header -sinsert %s:%s="%s" %s > /dev/null' \
                 % (platform_str,ckey,cval,filename)
        os.system(cmdstr)
Exemple #5
0
def get_sg_data(inputAcq, imouse):
    print("Retrieving self-gate data...")
    sgpts = get_dict_value(inputAcq.param_dict, 'np', 1) / 2 - get_dict_value(
        inputAcq.param_dict, 'nro', 1)
    if (sgpts < 1): return 0
    sg_fids, data_error = inputAcq.getdatafids(
        0,
        product(inputAcq.data_shape[0:-1]) / inputAcq.nrcvrs,
        rcvrnum=imouse,
        nrcvrs=inputAcq.nrcvrs,
        startpt=0,
        endpt=sgpts)
    return sg_fids
Exemple #6
0
def gen_kspace_local(inputAcq, ircvr, nTRs=None):
    print("Reading k-space data...")
    nrcvrs = inputAcq.nrcvrs
    no_ro = inputAcq.nro
    if ((no_ro <= 0) or (no_ro > inputAcq.data_shape[-1])):
        no_ro = inputAcq.data_shape[-1]  #np
    #if (len(inputAcq.data_shape)>2) and (inputAcq.data_shape[-3]>0):
    #    npe2 = inputAcq.data_shape[-3]
    #else:
    #    npe2 = 1
    #npe1 = inputAcq.data_shape[-2]
    if (inputAcq.platform == "Varian"):
        print("Not setup for Varian acquisition...")
        raise SystemExit
    elif (inputAcq.platform == "Bruker"
          ):  #force Bruker to artificial Varian format
        nf = nTRs
        nreps = rgf.get_dict_value(inputAcq.method_param_dict,
                                   "PVM_NRepetitions", 1)
    else:
        print("Input format not recognized.")
    raw_imgdata = zeros((nreps, 1, nf, no_ro), complex)
    for k in range(nreps):
        print("%d / %d" % (k, nreps))
        fid_start = k * nf
        fid_end = (k + 1) * nf
        fid_data, data_error = inputAcq.getdatafids(fid_start,
                                                    fid_end,
                                                    rcvrnum=ircvr)
        raw_imgdata[k, 0, :, :] = fid_data[:, -no_ro:]
        if (data_error):
            data_fraction = float(data_error + fid_start) / float(nf * nreps)
            print('Error at %f%% through data set' % (100.0 * data_fraction))
            break
    return raw_imgdata
Exemple #7
0
 def __init__(self, inputAcq, options, outputfile):
     self.options = options
     self.inputAcq = inputAcq
     self.outputfile = outputfile
     if ((self.options.petable == '') and (inputAcq.platform == "Varian")):
         self.petable_name = rgf.get_dict_value(inputAcq.param_dict,
                                                'petable', 'petable')
     elif ((self.options.petable == '')
           and (inputAcq.platform == "Bruker")):
         self.petable_name = rgf.get_dict_value(inputAcq.method_param_dict,
                                                'MICe_InputPetablePath',
                                                'petable')
     else:
         self.petable_name = self.options.petable
     self.kspace = None
     self.image_data = None
     self.Pftacq = False
Exemple #8
0
 def __init__(self,inputAcq,options,outputfile):
     self.options=options
     self.inputAcq=inputAcq
     self.outputfile=outputfile
     if ((self.options.petable=='') and (inputAcq.platform=="Varian")):
         self.petable_name=rgf.get_dict_value(inputAcq.param_dict,'petable','petable')
     else:
         self.petable_name=self.options.petable
     self.kspace=None
     self.image_data=None
    def gen_kspace(self, imouse=0):
        sgflag = rgf.get_dict_value(self.inputAcq.param_dict, 'sgflag', 'n')
        if (sgflag == 'y') and self.options.self_resp_gate:
            sg_fids = rsg.get_sg_data(self.inputAcq, imouse)
            #from pylab import plot,show
            #plot(sg_fids[:,3].real)
            #plot(sg_fids[:,3].imag)
            #show()
            tr = rgf.get_dict_value(self.inputAcq.param_dict, 'tr', 0.05)
            resp_dur = 0.2
            resp_gate_sig, resp_sig = rsg.self_resp_gate(sg_fids, tr, resp_dur)
        else:
            resp_gate_sig = None
            resp_sig = None
        if (self.options.petable_ordered_pairs):
            grappafov = int(
                rgf.get_dict_value(self.inputAcq.param_dict, 'grappafov', 1))
            self.kspace = rsg.gen_kspace_sg_orderedpairtable(
                self.inputAcq,
                resp_gate_sig,
                resp_sig,
                imouse,
                gate_resp=self.options.self_resp_gate,
                petable=self.petable_name,
                grappafov=grappafov,
                kpts_offset=self.options.grappa_kpts_offset,
                outputreps=self.options.outputreps,
                phasecorr=self.phasedriftcorr,
                dcpl_info=self.dcpl_info)
        elif (sgflag == 'y'):
            self.kspace = rsg.gen_kspace_sg(self.inputAcq, resp_gate_sig,
                                            resp_sig, imouse)
        else:  #sgflag='n' and no petable_ordered_pairs
            self.kspace = rgf.gen_kspace_simple(self.inputAcq, imouse)
        self.kspace = rgf.fov_adjustment(self.kspace, self.options,
                                         self.inputAcq, imouse)

        if self.options.fermi_ellipse:
            self.kspace = rgf.fermi_ellipse_filter(self.kspace)
        elif self.options.fermi_pecirc:
            self.kspace = rgf.fermi_pecircle_filter(self.kspace)
 def __init__(self, inputAcq, options, outputfile):
     self.options = options
     self.inputAcq = inputAcq
     self.outputfile = outputfile
     if ((self.options.petable == '') and (inputAcq.platform == "Varian")):
         self.petable_name = rgf.get_dict_value(inputAcq.param_dict,
                                                'petable', 'petable')
     else:
         self.petable_name = self.options.petable
     self.kspace = None
     self.image_data = None
     if (not self.options.dcplppeadj_string):
         self.dcplppeadj = None
     else:
         self.dcplppeadj = [
             float(x) for x in self.options.dcplppeadj_string.split(',')
         ]
Exemple #11
0
def gen_kspace_sg(inputAcq, resp_gate_sig, resp_sig, mousenum, gate_resp=True):
    print("Generating gated k-space data...")
    no_ro = inputAcq.data_shape[-1]
    if (get_dict_value(inputAcq.param_dict, 'sgflag', 'n') == 'y'):
        no_ro = get_dict_value(inputAcq.param_dict, 'nro', 0)
    nechoes = get_dict_value(inputAcq.param_dict, 'etl', 1)
    nfid_pts = inputAcq.data_shape[-1]
    no_inner_loop = 1  #int(get_dict_value(method_param_dict,'$PVM_NMovieFrames',1))
    no_middle_loop = 1  #int(get_dict_value(image_param_dict,'no_middle_loop','1'))
    no_outer_loop = int(get_dict_value(inputAcq.param_dict, 'nreps', 1))
    nexpt = no_inner_loop * no_middle_loop * no_outer_loop
    if (len(inputAcq.data_shape) > 2):
        n_slowpe = inputAcq.data_shape[-3]
    else:
        n_slowpe = 1
    n_fastpe = inputAcq.data_shape[-2]
    if (nechoes > 1):
        raw_imgdata = N.zeros((nechoes, n_slowpe, n_fastpe, no_ro), N.complex)
    else:
        raw_imgdata = N.zeros((n_slowpe, n_fastpe, no_ro), N.complex)
    traces_per_file = n_slowpe * n_fastpe * nexpt
    traces_per_slowpe = n_fastpe * no_inner_loop * no_middle_loop
    traces_per_fastpe = no_inner_loop
    #timing for echo locations
    sgpts = inputAcq.data_shape[-1] - get_dict_value(inputAcq.param_dict,
                                                     'nro', 1)
    start_pt = sgpts
    end_pt = inputAcq.data_shape[-1]
    nacq_pts = end_pt - start_pt
    if (nechoes > 1
        ):  #need to get this setup so that it finds or reads pts automatically
        #start_pt=[194,895]; end_pt=[578,1279]; nacq_pts=[384,384];
        start_pt = [61, 405]
        end_pt = [317, 661]
        nacq_pts = [256, 256]
        #[68,426] [324,682] [256,256]
    nrcvrs = inputAcq.nrcvrs
    #start_pt = int(0.5 + start_time*sw*1e-3*ro_oversample)
    #nacq_pts = int(0.45+no_ro*fracacqwindow/imgacqwindow)
    #end_pt = int(start_pt + ro_oversample*nacq_pts) #(echotimes+acqwindow/2.0)*sw*1e-3*ro_oversample
    for j in range(n_slowpe):
        print("%d / %d" % (j, n_slowpe))
        fid_data = zeros(
            (traces_per_slowpe * no_outer_loop, inputAcq.data_shape[-1]),
            complex)
        resp_flag = zeros((traces_per_slowpe * no_outer_loop, ), float)
        resp_curr_sig = zeros((traces_per_slowpe * no_outer_loop, ), float)
        for k in range(no_outer_loop):  #range(no_outer_loop)
            fid_start = j * traces_per_slowpe + k * traces_per_slowpe * n_slowpe
            fid_end = (
                j + 1) * traces_per_slowpe + k * traces_per_slowpe * n_slowpe
            fid_data_temp, data_error = inputAcq.getdatafids(fid_start,
                                                             fid_end,
                                                             rcvrnum=mousenum)
            if (data_error):
                data_fraction = float(j) / float(n_slowpe)
                print('Error at %f%% through data set' %
                      (100.0 * data_fraction))
                break
            fid_data[k * traces_per_slowpe:(k + 1) *
                     traces_per_slowpe, :] = fid_data_temp
            if (gate_resp):
                resp_flag[k * traces_per_slowpe:(k + 1) *
                          traces_per_slowpe] = resp_gate_sig[
                              fid_start:fid_end].astype(N.float)
                resp_curr_sig[k * traces_per_slowpe:(k + 1) *
                              traces_per_slowpe] = resp_sig[
                                  fid_start:fid_end].astype(N.float)
            else:
                resp_flag[k * traces_per_slowpe:(k + 1) *
                          traces_per_slowpe] = N.ones((traces_per_slowpe, ),
                                                      N.float)
        fid_shape = (no_outer_loop * no_middle_loop, n_fastpe,
                     traces_per_fastpe, inputAcq.data_shape[-1])
        resp_flag = N.reshape(resp_flag, fid_shape[:-1])
        resp_curr_sig = N.reshape(resp_curr_sig, fid_shape[:-1])
        fid_data = N.reshape(fid_data, fid_shape)
        norm_val = N.sum(N.sum(resp_flag, axis=0), axis=1)
        zero_inds = N.nonzero(norm_val == 0)[0]
        for index in zero_inds:
            print("|")
            best_index = argmin(ravel(resp_curr_sig[:, index, :]))
            resp_flag[best_index / traces_per_fastpe, index,
                      best_index % traces_per_fastpe] = 1
        norm_val = N.sum(N.sum(resp_flag, axis=0), axis=1)
        if (nechoes <= 1):
            raw_imgdata[j,:,-nacq_pts:] = ( N.sum(N.sum( fid_data[:,:,:,start_pt:end_pt]* \
                                                         resp_flag[:,:,N.newaxis]       \
                                                        ,axis=0),axis=1)/norm_val[:,N.newaxis]).astype(N.complex)
        else:
            for k in range(nechoes):
                raw_imgdata[k,j,:,-nacq_pts[k]:] = ( N.sum(N.sum( fid_data[:,:,:,start_pt[k]:end_pt[k]]* \
                                                                  resp_flag[:,:,N.newaxis]       \
                                                                 ,axis=0),axis=1)/norm_val[:,N.newaxis]).astype(N.complex)

    return raw_imgdata
Exemple #12
0
def gen_kspace_sg_orderedpairtable(inputAcq,
                                   resp_gate_sig,
                                   resp_sig,
                                   mousenum,
                                   gate_resp=True,
                                   petable=None,
                                   petable_arrays=('t1', 't2'),
                                   grappafov=1,
                                   kpts_offset=0,
                                   outputreps=False,
                                   phasecorr=None,
                                   dcpl_info=None):
    print("Generating gated k-space data...")
    no_ro = inputAcq.data_shape[-1]
    if (get_dict_value(inputAcq.param_dict, 'sgflag', 'n') == 'y'):
        no_ro = get_dict_value(inputAcq.param_dict, 'nro', 0)
    nechoes = get_dict_value(inputAcq.param_dict, 'etl', 1)
    nfid_pts = inputAcq.data_shape[-1]
    nv = int(get_dict_value(inputAcq.param_dict, 'nv', 1))
    nv2 = int(get_dict_value(inputAcq.param_dict, 'nv2', 1))
    if (petable):
        t1array = parse_petable_file(petable, petable_arrays[0])
        t2array = parse_petable_file(petable, petable_arrays[1])
    else:
        t1array = (N.arange(nv * nv2) % nv) - nv // 2 + 1
        t2array = (N.arange(nv * nv2) // nv) - nv2 // 2 + 1
    if (outputreps):
        gate_resp = False  #only makes sense to output reps without retrospective gating
        noutreps = int(
            mode(
                array(
                    collections.Counter(
                        t1array + nv // 2 - 1 + nv *
                        (t2array + nv2 // 2 - 1)).most_common())[:, 1])[0]
            [0])  #count from table rather than looking in procpar
    else:
        noutreps = 1
    if (nechoes * noutreps > 1):
        raw_imgdata = N.zeros((nechoes * noutreps, nv2, nv, no_ro), N.complex)
    else:
        raw_imgdata = N.zeros((nv2, nv, no_ro), N.complex)
    #timing for echo locations needs to be improved
    if (dcpl_info == None):
        start_pt = [inputAcq.data_shape[-1] - no_ro]
        end_pt = [inputAcq.data_shape[-1]]
    else:
        start_pt = [dcpl_info.rok0index - no_ro // 2]  #[0]
        end_pt = []
        for this_start_pt in start_pt:
            end_pt += [this_start_pt + no_ro]

    nacq_pts = [end_pt[0] - start_pt[0]]
    if (nechoes > 1
        ):  #need to get this setup so that it finds or reads pts automatically
        #start_pt=[194,895]; end_pt=[578,1279]; nacq_pts=[384,384];
        print('Warning: echo timing needs to be setup properly...')
        start_pt = [61, 405]
        end_pt = [317, 661]
        nacq_pts = [256, 256]
        #[68,426] [324,682] [256,256]
    nrcvrs = inputAcq.nrcvrs
    #start_pt = int(0.5 + start_time*sw*1e-3*ro_oversample)
    #nacq_pts = int(0.45+no_ro*fracacqwindow/imgacqwindow)
    #end_pt = int(start_pt + ro_oversample*nacq_pts) #(echotimes+acqwindow/2.0)*sw*1e-3*ro_oversample
    for j in range(nv2):
        print("%d / %d" % (j, nv2))
        for k in range(nv):
            fidinds = N.nonzero((t2array == (
                (j - nv2 // 2 + 1) * grappafov + kpts_offset)) & (t1array == (
                    (k - nv // 2 + 1) * grappafov + kpts_offset)))[0]
            #print "gen_kspace_sg_orderedpairtable: ",len(fidinds)
            if (len(fidinds) == 0):
                continue
            nreps = len(fidinds)
            fid_data = zeros((nreps, inputAcq.data_shape[-1]), complex)  #no_ro
            for q in range(nreps):
                #fid_data[q,:],data_error = get_vnmr_datafids(vnmrfidfilelist,fidinds[q],fidinds[q]+1,
                #                                             header_info,startpt=start_pt[0],endpt=end_pt[0],mouse_num=mousenum,nrcvrs=nrcvrs)
                fid_data[q, :] = get_corrected_datafids(inputAcq,
                                                        fidinds[q],
                                                        fidinds[q] + 1,
                                                        mouse_num=mousenum,
                                                        phasecorr=phasecorr,
                                                        dcpl_info=dcpl_info,
                                                        dcpl_ppe_index=k -
                                                        nv / 2 + 1)
            if (gate_resp):
                resp_flag = resp_gate_sig[fidinds].astype(N.int)
                resp_curr_sig = resp_sig[fidinds].astype(N.float)
            else:
                resp_flag = N.ones((nreps, ), bool)
            norm_val = N.sum(resp_flag)
            if (norm_val == 0):
                print("|")
                best_index = argmin(resp_curr_sig)
                resp_flag[best_index] = 1
                norm_val = 1
            if (nechoes * noutreps <= 1):
                raw_imgdata[j,k,-nacq_pts[0]:] = N.sum( fid_data[:,start_pt[0]:end_pt[0]]*resp_flag[:,N.newaxis]   \
                                                       ,axis=0)/norm_val
            else:
                repstep = nreps // noutreps
                rstarts = arange(noutreps) * repstep
                rends = (1 + arange(noutreps)) * repstep
                rends = where(rends == rstarts, rstarts + 1, rends)
                rends[-1] = len(fidinds)
                for cr in range(noutreps):
                    for q in range(nechoes):
                        raw_imgdata[cr*nechoes+q,j,k,-nacq_pts[q]:] = N.sum( fid_data[rstarts[cr]:rends[cr],
                                                                                      start_pt[q]:end_pt[q]]*resp_flag[rstarts[cr]:rends[cr],N.newaxis]       \
                                                                            ,axis=0)/N.sum(resp_flag[rstarts[cr]:rends[cr]])
    return raw_imgdata
Exemple #13
0
def write_to_mnc_file(filename,
                      data,
                      inputAcq,
                      options,
                      manstarts=None,
                      mansteps=None,
                      imouse=0,
                      mincversion=2):
    #output type
    nrcvrs_per_mouse = len(N.nonzero(inputAcq.rcvrmouse_mapping == imouse)[0])
    if options.real:
        if (data.dtype == complex):
            out_im = data.real
        else:
            out_im = data
        vType = [options.vType, "short"][options.vType == None]
    elif options.imag:
        out_im = data.imag
        vType = [options.vType, "short"][options.vType == None]
    elif options.phase:
        out_im = N.arctan2(data.imag, data.real)
        vType = [options.vType, "short"][options.vType == None]
    elif (nrcvrs_per_mouse > 1):
        print("Sum of squares reconstruction on multiple coils...")
        if ((inputAcq.nD == 3)
                or ((inputAcq.nD == 2) and (inputAcq.nslices > 1))):
            rcvraxis = -4
        elif ((inputAcq.nD == 2) and (inputAcq.nslices == 1)):
            rcvraxis = -3
        elif (len(data.shape) > 3):
            rcvraxis = -4
        else:
            rcvraxis = 0
        if (len(data.shape) > inputAcq.nD):
            out_im = N.sqrt(N.sum(abs(data)**2, axis=rcvraxis))
        else:  #assume only one coil has been received and that nD==ndims
            out_im = abs(data)
        vType = [options.vType, "ushort"][options.vType == None]
    else:
        out_im = abs(data)
        vType = [options.vType, "ushort"][options.vType == None]
    #dimensions (number and sizes)
    if (len(out_im.shape) > 4):
        out_im.shape = (N.prod(out_im.shape[0:(len(out_im.shape) - 3)]),
                        out_im.shape[-3], out_im.shape[-2], out_im.shape[-1])
    dim_sizes = out_im.shape
    nD = len(dim_sizes)
    if (nD == 2):
        nout_files = 1
        dim_sizes = (1, dim_sizes[0], dim_sizes[1])
        out_im.shape = dim_sizes
    elif (nD < 4):
        nout_files = 1
    else:
        nout_files = dim_sizes[0]
        nD = 3
    if (inputAcq.platform == "Varian"):
        #fov and step size
        fov_array = [
            10.0 * float(get_dict_value(inputAcq.param_dict, x, 1.0))
            for x in ['lpe2', 'lpe', 'lro']
        ]
        (fov_ro, fov_pe, fov_pe2) = (fov_array[-1], fov_array[-2],
                                     fov_array[-3])
        #step & direction
        step_list = [
            fov_pe2 / dim_sizes[-3], fov_pe / dim_sizes[-2],
            fov_ro / dim_sizes[-1], 1, 1
        ]
        [psi, phi, theta] = [
            get_dict_value(inputAcq.param_dict, x, 0)
            for x in ['psi', 'phi', 'theta']
        ]
        Emat = Eulermat(psi * N.pi / 180, phi * N.pi / 180,
                        theta * N.pi / 180)  #did this end up Varian specific??
        dim_names = ['zspace', 'yspace', 'xspace']  #default
        for j in range(3):
            dim_names[-1 - j] = ['xspace', 'yspace',
                                 'zspace'][N.argmax(abs(Emat[:, j]))]
            if (Emat[N.argmax(abs(Emat[:, j])), j] < 0):
                step_list[2 - j] = step_list[2 - j] * (-1)
        #start point
        mm_pro = 10.0 * get_dict_value(
            inputAcq.param_dict, 'mm_pro',
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        mm_ppe = 10.0 * get_dict_value(
            inputAcq.param_dict, 'mm_ppe',
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        mm_ppe2 = 10.0 * get_dict_value(
            inputAcq.param_dict, 'mm_ppe2',
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        start_list = [
            N.sign(step_list[0]) * mm_ppe2[imouse] - step_list[0] *
            (0.5 * dim_sizes[-3] - 0.5),
            N.sign(step_list[1]) * mm_ppe[imouse] - step_list[1] *
            (0.5 * dim_sizes[-2] - 0.5),
            N.sign(step_list[2]) * mm_pro[imouse] - step_list[2] *
            (0.5 * dim_sizes[-1] - 0.5), 0, 0
        ]
    elif (inputAcq.platform == "Bruker"):
        #fov and step size
        fov_array = (get_dict_value(inputAcq.method_param_dict, "PVM_Fov",
                                    N.array([20.0, 20.0, 20.0],
                                            float)).astype(float))[::-1]
        (fov_ro, fov_pe) = (fov_array[-1], fov_array[-2])
        if (inputAcq.nD == 3):
            fov_pe2 = fov_array[-3]
        elif (inputAcq.nD == 2):
            fov_pe2 = get_dict_value(
                inputAcq.method_param_dict, "PVM_SPackArrSliceDistance",
                N.array([1.0, 1.0, 1.0], float))[0] * inputAcq.nslices
        #step & direction
        dim_names = ['zspace', 'yspace', 'xspace']
        stepdirec = N.ones(3)
        Gmatrix_parse_row = lambda x: (['xspace', 'yspace', 'zspace'][N.argmax(
            abs(x))], [1, -1][x[N.argmax(abs(x))] < 0])
        dim_names[0], stepdirec[0] = Gmatrix_parse_row(inputAcq.gmatrix[2])
        dim_names[1], stepdirec[1] = Gmatrix_parse_row(inputAcq.gmatrix[1])
        dim_names[2], stepdirec[2] = Gmatrix_parse_row(inputAcq.gmatrix[0])
        #dim_names=['zspace','yspace','xspace']    #default
        #sliceorient=get_dict_value(inputAcq.method_param_dict,'PVM_SPackArrSliceOrient',['axial'])[0]
        #dim_names[0]={'sagittal': 'xspace', 'coronal': 'yspace', 'axial': 'zspace'}[sliceorient]
        #readorient=get_dict_value(inputAcq.method_param_dict,'PVM_SPackArrReadOrient',['H_F'])[0]
        #dim_names[2]={'H_F': 'zspace','L_R': 'xspace', 'D_V': 'yspace'}[readorient] #what is yspace flag??? can we have F_H???
        #dim_names[1]=list(set(['zspace','yspace','xspace'])-set([dim_names[0],dim_names[2]]))[0]
        step_list = [
            fov_pe2 * stepdirec[-3] / dim_sizes[-3],
            fov_pe * stepdirec[-2] / dim_sizes[-2],
            fov_ro * stepdirec[-1] / dim_sizes[-1], 1, 1
        ]
        #start point
        mm_pro = get_dict_value(inputAcq.method_param_dict, 'MICe_ReadOffset',
                                N.array([0.0, 0.0, 0.0, 0.0], float))
        mm_ppe = get_dict_value(inputAcq.method_param_dict,
                                'MICe_Phase1Offset',
                                N.array([0.0, 0.0, 0.0, 0.0], float))
        if (inputAcq.nD == 3):
            #mm_ppe2 = get_dict_value(inputAcq.method_param_dict,'MICe_Phase2Offset',N.array([0.0,0.0,0.0,0.0],float))
            mm_ppe2 = get_dict_value(inputAcq.method_param_dict,
                                     'MICe_SliceOffset',
                                     N.array([0.0, 0.0, 0.0, 0.0], float))
        elif (inputAcq.nD == 2):
            mm_ppe2 = get_dict_value(inputAcq.method_param_dict,
                                     'MICe_SliceOffset',
                                     N.array([0.0, 0.0, 0.0, 0.0], float))
        else:
            mm_ppe2 = N.array([0.0, 0.0, 0.0, 0.0], float)
        start_list = [
            N.sign(step_list[0]) * mm_ppe2[imouse] - step_list[0] *
            (0.5 * dim_sizes[-3] - 0.5),
            N.sign(step_list[1]) * mm_ppe[imouse] - step_list[1] *
            (0.5 * dim_sizes[-2] - 0.5),
            N.sign(step_list[2]) * mm_pro[imouse] - step_list[2] *
            (0.5 * dim_sizes[-1] - 0.5), 0, 0
        ]
    else:
        print("Platform not recognized as Varian or Bruker")
    if (options.fft2d):
        #loop order: slice,pe1,ro
        if (inputAcq.platform == "Varian"):
            slice_sep = float(get_dict_value(
                inputAcq.param_dict, 'thk',
                1.0))  #this isn't strictly the right parameter to use...
        elif (inputAcq.platform == "Bruker"):
            slice_sep = float(
                get_dict_value(inputAcq.method_param_dict,
                               'PVM_SPackArrSliceDistance', [0.0])[0])
        start_list[0] = -dim_sizes[
            -3] * slice_sep / 2.0  #this is not set up properly for 2D imaging yet...
        step_list[0] = slice_sep
    elif (options.nofft):  #nofft
        if (fov_pe2 > 1e-6):
            steppe2 = 1.0 / fov_pe2
            startpe2 = -dim_sizes[-3] * steppe2 / 2
        else:
            steppe2 = 1.0
            startpe2 = 0
        step_list = [steppe2, 1.0 / fov_pe, 1.0 / fov_ro, 1, 1]
        start_list = [
            startpe2, -dim_sizes[-2] / fov_pe, -dim_sizes[-1] / fov_ro
        ]
    #intensity scaling
    if (options.image_range_max - options.image_range_min > 1e-4):
        print("Using user-input intensity range...")
        (Imin, Imax) = (options.image_range_min, options.image_range_max)
        for j in range(dim_sizes[0]):
            out_im[j] = N.where(N.greater(out_im[j], options.image_range_max),
                                options.image_range_max,
                                out_im[j]).astype(float)
            out_im[j] = N.where(N.less(out_im[j], options.image_range_min),
                                options.image_range_min,
                                out_im[j]).astype(float)
    else:
        N_voxels = N.size(out_im)
        flat_out = N.reshape(out_im, (N_voxels, ))
        Imin = min(flat_out)
        if options.max_range:
            Imax = max(flat_out)
        else:
            plane_maxima = N.ravel(N.maximum.reduce(out_im, axis=-1))
            plane_maxima = medfilt(plane_maxima, 11)
            Imax = 1.1 * N.maximum.reduce(plane_maxima)
            indices = N.nonzero(N.greater(flat_out, Imax))
            N.put(flat_out, indices, Imax)
    #override of starts and steps
    if (manstarts != None):
        start_list = list(manstarts)
    if (mansteps != None):
        step_list = list(mansteps)
    #loop over output files
    for j in range(nout_files):
        #index output (for multiple echoes, repetitions, phases, etc)
        if (nout_files == 1):
            outfile_name = filename
            imgshape = dim_sizes
        else:
            outfile_name = filename[:-4] + '_' + str(j) + '.mnc'
            imgshape = dim_sizes[1:]
        print("Writing to output file %s..." % outfile_name)
        #minc1 or minc2 output
        if (mincversion != 2):
            print("Sorry, minc1 isn't an option.")

        spatDim = 3
        #print outfile_name,dim_names,imgshape,tuple(start_list[0:spatDim]),tuple(step_list[0:spatDim]),vType,out_im.dtype,out_im.shape
        mnc_vol = volumeFromDescription(outfile_name,
                                        dim_names,
                                        imgshape,
                                        tuple(start_list[0:spatDim]),
                                        tuple(step_list[0:spatDim]),
                                        volumeType=vType,
                                        dtype=out_im.dtype)
        if (nout_files == 1):
            mnc_vol.setdata(out_im)
        else:
            mnc_vol.setdata(out_im[j])
        mnc_vol.writeFile()
        mnc_vol.closeVolume()
        #add scan params to mnc header
        add_scanparams_to_mncheader(inputAcq, outfile_name, imouse)
    return nout_files