Exemple #1
0
    def compute(self):

        import os
        import time
        import numpy as np

        # start file browser
        fname = gpi.TranslateFileURI(self.getVal('File Browser'))

        # check that the path actually exists
        if not os.path.exists(fname):
            self.log.node("Path does not exist: " + str(fname))
            return 0

        # show some file stats
        fstats = os.stat(fname)
        # creation
        ctime = time.strftime('%d/%m/20%y', time.localtime(fstats.st_ctime))
        # mod time
        mtime = time.strftime('%d/%m/20%y', time.localtime(fstats.st_mtime))
        # access time
        atime = time.strftime('%d/%m/20%y', time.localtime(fstats.st_atime))
        # filesize
        fsize = fstats.st_size
        # user id
        uid = fstats.st_uid
        # group id
        gid = fstats.st_gid

        # read the data
        # takes the base filename
        fname = os.path.splitext(fname)[0]
        out = cfl.readcfl(fname)

        if self.getVal('Squeeze'):
            out = out.squeeze()

        d1 = list(out.shape)
        info = "created: "+str(ctime)+"\n" \
               "accessed: "+str(atime)+"\n" \
               "modified: "+str(mtime)+"\n" \
               "UID: "+str(uid)+"\n" \
               "GID: "+str(gid)+"\n" \
               "file size (bytes): "+str(fsize)+"\n" \
               "dimensions: "+str(d1)+"\n" \
               "type: "+str(out.dtype)+"\n"
        self.setAttr('I/O Info:', val=info)

        self.setData('out', out)

        return (0)
Exemple #2
0
    def compute(self):
        fullpath = gpi.TranslateFileURI(self.getVal('output-file'))
        filetype, ext = file_types[self.getVal('file-type')]
        fullpath += ext

        data = self.getData('in')
        affine = self.getData('affine')

        if self.getVal('reverse-dims'):
            data = data.T

        if affine is None:
            affine = np.eye(4)

        nibabel_image = filetype(data, affine)  # add header?
        nibabel_image.to_filename(fullpath)

        return 0
    def compute(self):
        # start file browser
        fname = gpi.TranslateFileURI(self.getVal('input-file'))

        # check that the path actually exists
        if not os.path.exists(fname):
            self.log.node("Path does not exist: " + str(fname))
            return 0

        nibabel_image = nib.load(fname)

        out_data = nibabel_image.get_data()
        if self.getVal('reverse-dims'):
            out_data = out_data.T

        self.setData('image', out_data)
        self.setData('affine', nibabel_image.affine)

        return (0)
Exemple #4
0
    def make_event_holders(self):
        """Make appropriate Holder objects depending on the Event type."""

        self.system = self.in_dict['system']
        # arbgrad_file_path is only for arbitrary gradients
        arbgrad_file_path = self.all_event_def[
            'file_path'] if 'file_path' in self.all_event_def else None
        self.all_event_holders = {}

        for event in self.all_event_def:
            event_unique_name = event['event_unique_name']
            event_name = event['event_name']
            event_values = list(event['event_values'].values())
            include_in_loop = event['include_in_loop']

            if event_name == 'Delay':
                params = self.parse_config_params(event_values)
                delay = makedelay(params[0])
                self.all_event_holders[
                    event_unique_name] = delay, include_in_loop
            elif event_name == 'SincRF':
                include_gz = event['include_gz']
                max_grad, max_slew, flip_angle, duration, freq_offset, phase_offset, time_bw_product, apodization, slice_thickness = self.parse_config_params(
                    event_values)
                flip_angle = math.radians(flip_angle)
                max_grad = convert.convert_from_to(max_grad, 'mT/m')
                max_slew = convert.convert_from_to(max_slew, 'mT/m/ms')
                max_grad = self.system.max_grad if max_grad == 0 else max_grad
                max_slew = self.system.max_slew if max_slew == 0 else max_slew
                kwargs_for_sinc = {
                    "flip_angle": flip_angle,
                    "system": self.system,
                    "duration": duration,
                    "freq_offset": freq_offset,
                    "phase_offset": phase_offset,
                    "time_bw_product": time_bw_product,
                    "apodization": apodization,
                    "max_grad": max_grad,
                    "max_slew": max_slew,
                    "slice_thickness": slice_thickness
                }
                if include_gz:
                    rf, gz = makesincpulse(kwargs_for_sinc, 2)
                    self.all_event_holders[
                        event_unique_name] = rf, include_in_loop
                    self.all_event_holders[
                        'gz_' + event_unique_name] = gz, include_in_loop
                else:
                    rf = makesincpulse(kwargs_for_sinc)
                    self.all_event_holders[
                        event_unique_name] = rf, include_in_loop
            elif event_name == 'BlockRF':
                include_gz = event['include_gz']
                max_grad, max_slew, flip_angle, duration, freq_offset, phase_offset, time_bw_product, bandwidth, slice_thickness = self.parse_config_params(
                    event_values)
                flip_angle = math.radians(flip_angle)
                max_grad = convert.convert_from_to(max_grad, 'mT/m')
                max_slew = convert.convert_from_to(max_slew, 'mT/m/ms')
                max_grad = self.system.max_grad if max_grad == 0 else max_grad
                max_slew = self.system.max_slew if max_slew == 0 else max_slew
                kwargs_for_block = {
                    "flip_angle": flip_angle,
                    "system": self.system,
                    "duration": duration,
                    "freq_offset": freq_offset,
                    "phase_offset": phase_offset,
                    "time_bw_product": time_bw_product,
                    "bandwidth": bandwidth,
                    "max_grad": max_grad,
                    "max_slew": max_slew,
                    "slice_thickness": slice_thickness
                }
                if include_gz:
                    rf, gz = makeblockpulse(kwargs_for_block, 2)
                    self.all_event_holders[
                        event_unique_name] = rf, include_in_loop
                    self.all_event_holders[
                        'gz_' + event_unique_name] = gz, include_in_loop
                else:
                    rf = makeblockpulse(kwargs_for_block)
                    self.all_event_holders[
                        event_unique_name] = rf, include_in_loop
            elif event_name == 'G':
                channel = event_values.pop(0)
                max_grad, max_slew, duration, area, flat_time, flat_area, amplitude, rise_time = self.parse_config_params(
                    event_values)

                # area, flat_area and amplitude should be reset to -1 if user does not input any values. This is
                # because the default values are -1 in maketrap method.
                area = area if area != 0 else -1
                flat_area = flat_area if flat_area != 0 else -1
                amplitude = amplitude if amplitude != 0 else -1

                max_grad = convert.convert_from_to(max_grad, 'mT/m')
                max_slew = convert.convert_from_to(max_slew, 'mT/m/ms')
                max_grad = self.system.max_grad if max_grad == 0 else max_grad
                max_slew = self.system.max_slew if max_slew == 0 else max_slew
                kwargs_for_trap = {
                    "channel": channel,
                    "system": self.system,
                    "duration": duration,
                    "area": area,
                    "flat_time": flat_time,
                    "flat_area": flat_area,
                    "amplitude": amplitude,
                    "max_grad": max_grad,
                    "max_slew": max_slew,
                    "rise_time": rise_time
                }
                trap = maketrapezoid(kwargs_for_trap)
                self.all_event_holders[
                    event_unique_name] = trap, include_in_loop
            elif event_name == 'GyPre':
                duration, area = self.parse_config_params(event_values)
                Ny = self.system.Ny
                delta_k = 1 / self.system.fov
                gy_pre_list = []

                for i in range(int(Ny)):
                    kwargs_for_gy_pre = {
                        "channel": 'y',
                        "system": self.system,
                        "area": (i - Ny / 2) * delta_k,
                        "duration": duration
                    }
                    if area != 0:
                        kwargs_for_gy_pre['area'] = area
                    gy_pre = maketrapezoid(kwargs_for_gy_pre)
                    gy_pre_list.append(gy_pre)

                self.all_event_holders[event_unique_name] = gy_pre_list, True
            elif event_name == 'ArbGrad':
                channel = event_values.pop(0)
                max_grad, max_slew = self.parse_config_params(event_values)
                file = h5py.File(gpi.TranslateFileURI(arbgrad_file_path), "r")
                self.dataset = str()

                def append_if_dataset(name, obj):
                    if isinstance(obj, h5py.Dataset):
                        self.dataset = name
                        return True

                file.visititems(append_if_dataset)

                waveform = file[self.dataset].value
                kwargs_for_arb_grad = {
                    "channel": channel,
                    "waveform": waveform,
                    "max_grad": max_grad,
                    "max_slew": max_slew,
                    "system": self.system
                }
                arb_grad = makearbitrarygrad(kwargs_for_arb_grad)
                self.all_event_holders[
                    event_unique_name] = arb_grad, include_in_loop
            elif event_name == 'ADC':
                num_samples, dwell, duration, delay, freq_offset, phase_offset = self.parse_config_params(
                    event_values)
                kwargs_for_adc = {
                    "num_samples": num_samples,
                    "system": self.system,
                    "dwell": dwell,
                    "duration": duration,
                    "delay": delay,
                    "freq_offset": freq_offset,
                    "phase_offset": phase_offset
                }
                adc = makeadc(kwargs_for_adc)
                self.all_event_holders[
                    event_unique_name] = adc, include_in_loop
Exemple #5
0
    def compute(self):

        do_squeeze = self.getVal('Squeeze')
        do_remos = self.getVal('Remove Oversampling')
        do_zeropad = self.getVal('Zeropad')
        do_noiseadj = self.getVal('Noise Adjust')
        receiver_noise_bw = self.getVal('Receiver Noise BW Ratio')

        #Get the file name use the file browser widget
        fname = gpi.TranslateFileURI(self.getVal('File Browser'))

        #Check if the file exists
        if not os.path.exists(fname):
            self.log.node("Path does not exist: "+str(fname))
            return 0
        
        dset = ismrmrd.Dataset(fname, 'dataset', create_if_needed=False)

        xml_header = dset.read_xml_header()
        header = ismrmrd.xsd.CreateFromDocument(xml_header)
        self.setData('ISMRMRDHeader', str(xml_header))

        enc = header.encoding[0]

        # Matrix size
        eNx = enc.encodedSpace.matrixSize.x
        eNy = enc.encodedSpace.matrixSize.y
        eNz = enc.encodedSpace.matrixSize.z
        rNx = enc.reconSpace.matrixSize.x
        rNy = enc.reconSpace.matrixSize.y
        rNz = enc.reconSpace.matrixSize.z

        # Field of View
        eFOVx = enc.encodedSpace.fieldOfView_mm.x
        eFOVy = enc.encodedSpace.fieldOfView_mm.y
        eFOVz = enc.encodedSpace.fieldOfView_mm.z
        rFOVx = enc.reconSpace.fieldOfView_mm.x
        rFOVy = enc.reconSpace.fieldOfView_mm.y
        rFOVz = enc.reconSpace.fieldOfView_mm.z

        # Number of Slices, Reps, Contrasts, etc.
        ncoils = header.acquisitionSystemInformation.receiverChannels
        if enc.encodingLimits.slice != None:
            nslices = enc.encodingLimits.slice.maximum + 1
        else:
            nslices = 1
            
        if enc.encodingLimits.repetition != None:
            nreps = enc.encodingLimits.repetition.maximum + 1
        else:
            nreps = 1
        
        if enc.encodingLimits.contrast != None:
            ncontrasts = enc.encodingLimits.contrast.maximum + 1
        else:
            ncontrasts = 1


        # In case there are noise scans in the actual dataset, we will skip them.
        noise_data = list()
        noise_dmtx = None
        
        firstacq=0
        for acqnum in range(dset.number_of_acquisitions()):
            acq = dset.read_acquisition(acqnum)
            
            if acq.isFlagSet(ismrmrd.ACQ_IS_NOISE_MEASUREMENT):
                noise_data.append((acq.getHead(),acq.data))
                continue
            else:
                firstacq = acqnum
                break    

        if len(noise_data):
            profiles = len(noise_data)
            channels = noise_data[0][1].shape[0]
            samples_per_profile = noise_data[0][1].shape[1]
            noise = np.zeros((channels,profiles*samples_per_profile),dtype=np.complex64)
            counter = 0
            for p in noise_data:
                noise[:,counter*samples_per_profile:(counter*samples_per_profile+samples_per_profile)] = p[1]
                counter = counter + 1
                
            self.setData('noise',noise)
            
            scale = (acq.sample_time_us/noise_data[0][0].sample_time_us)*receiver_noise_bw
            noise_dmtx = coils.calculate_prewhitening(noise,scale_factor=scale)
            noise_data = list()
            
        # Empty array for the output data
        acq = dset.read_acquisition(firstacq)
        ro_length = acq.number_of_samples
        padded_ro_length = (acq.number_of_samples-acq.center_sample)*2

        
        size_nx = 0
        if do_remos:
            size_nx = rNx
            do_zeropad = True
        elif do_zeropad:
            size_nx = padded_ro_length
        else:
            size_nx = ro_length
            
        all_data = np.zeros((nreps, ncontrasts, nslices, ncoils, eNz, eNy, size_nx), dtype=np.complex64)

        # Loop through the rest of the acquisitions and stuff
        for acqnum in range(firstacq,dset.number_of_acquisitions()):
            acq = dset.read_acquisition(acqnum)

            acq_data_prw = np.zeros(acq.data.shape,dtype=np.complex64)
            acq_data_prw[:] = acq.data[:]
            
            if do_noiseadj and (noise_dmtx is not None):
                acq_data_prw = coils.apply_prewhitening(acq_data_prw, noise_dmtx)
 
            data2 = None
            
            if (padded_ro_length != ro_length) and do_zeropad: #partial fourier
                data2 = np.zeros((acq_data_prw.shape[0], padded_ro_length),dtype=np.complex64)
                offset = (padded_ro_length>>1)  - acq.center_sample
                data2[:,0+offset:offset+ro_length] = acq_data_prw
            else:
                data2 = acq_data_prw

            if do_remos:
                data2=transform.transform_kspace_to_image(data2,dim=(1,))
                data2=data2[:,(padded_ro_length>>2):(padded_ro_length>>2)+(padded_ro_length>>1)]
                data2=transform.transform_image_to_kspace(data2,dim=(1,)) * np.sqrt(float(padded_ro_length)/ro_length)
                
            # Stuff into the buffer
            rep = acq.idx.repetition
            contrast = acq.idx.contrast
            slice = acq.idx.slice
            y = acq.idx.kspace_encode_step_1
            z = acq.idx.kspace_encode_step_2
            
            all_data[rep, contrast, slice, :, z, y, :] = data2
                
        all_data = all_data.astype('complex64')

        if do_squeeze:
            all_data = np.squeeze(all_data)

        
        self.setData('data',all_data)
        
        return 0