Esempio n. 1
0
    def xtomo_exchange(
        self,
        data,
        data_white=None,
        data_dark=None,
        theta=None,
        data_exchange_type=None,
        source_name=None,
        source_mode=None,
        source_datetime=None,
        beamline=None,
        energy=None,
        current=None,
        actual_pixel_size=None,
        experimenter_name=None,
        experimenter_affiliation=None,
        experimenter_email=None,
        instrument_comment=None,
        sample_name=None,
        sample_comment=None,
        acquisition_mode=None,
        acquisition_comment=None,
        sample_position_x=None,
        sample_position_y=None,
        sample_position_z=None,
        sample_image_shift_x=None,
        sample_image_shift_y=None,
        image_exposure_time=None,
        image_time=None,
        image_theta=None,
        hdf5_file_name=None,
        axes="theta:y:x",
        log="INFO",
    ):
        """ 
        Write 3-D data to a data-exchange file.

        Parameters
                    
        data : ndarray
            3-D X-ray absorption tomography raw data.
            Size of the dimensions should be:
            [projections, slices, pixels].
            
        data_white, data_dark : ndarray, optional
            3-D white-field/dark_field data. Multiple
            projections are stacked together to obtain
            a 3-D matrix. 2nd and 3rd dimensions should
            be the same as data: [shots, slices, pixels].
            
        theta : ndarray, optional
            Data acquisition angles corresponding
            to each projection.

        data_excahnge_type : str, optional
            label defyining the type of data contained in data exchange file
            for raw data tomography data use 'tomography_raw_projections'

        source_name, source_mode, source_datetime : str, optional
            label defining the source name, operation mode and date/time when these values were taken

        beamline : str, optional
            label defining the beamline name
        
        energy, current : float, optional
            X-ray energy and bean current

        actual_pixel_size : float, optional
            pixel size on the sample plane
 
        experimenter_name, experimenter_affiliation, experimenter_email : str, optional
            user name, affiliation and e-mail address

        instrument_comment : str, optional
            instrument comment

        sample_name, sample_comment : str, optional
            sample name and comment
        
        acquisition_mode, acquisition_comment : str, optional
            acquisition mode and comment

        hd5_file_name : str
            Output file.

        Notes
        -----
        If file exists, does nothing
                
        Examples
        
        - Convert tomographic projection series (raw, dark, white)  of tiff in data exchange:
            
            >>> import dataexchange

            >>> file_name = '/local/dataraid/databank/Anka/radios/image_.tif'
            >>> dark_file_name = '/local/dataraid/databank/Anka/darks/image_.tif'
            >>> white_file_name = '/local/dataraid/databank/Anka/flats/image_.tif'

            >>> hdf5_file_name = '/local/dataraid/databank/dataExchange/tmp/Anka.h5'

            >>> projections_start = 0
            >>> projections_end = 3167
            >>> white_start = 0
            >>> white_end = 100
            >>> dark_start = 0
            >>> dark_end = 100

            >>> sample_name = 'Anka'
            >>> 
            >>> # Read raw data
            >>> read = dataexchange.Import()
            >>> data, white, dark, theta = read.xtomo_raw(file_name,
            >>>                                                    projections_start = projections_start,
            >>>                                                    projections_end = projections_end,
            >>>                                                    white_file_name = white_file_name,
            >>>                                                    white_start = white_start,
            >>>                                                    white_end = white_end,
            >>>                                                    dark_file_name = dark_file_name,
            >>>                                                    dark_start = dark_start,
            >>>                                                    dark_end = dark_end,
            >>>                                                    projections_digits = 5,
            >>>                                                    log='INFO'
            >>>                                                    )
            >>>
            >>> # Save data
            >>> write = dataexchange.Export()
            >>> write.xtomo_exchange(data = data,
            >>>                       data_white = white,
            >>>                       data_dark = dark,
            >>>                       theta = theta,
            >>>                       hdf5_file_name = hdf5_file_name,
            >>>                       data_exchange_type = 'tomography_raw_projections',
            >>>                       sample_name = sample_name
            >>>                       )

        """

        if hdf5_file_name != None:
            if os.path.isfile(hdf5_file_name):
                self.logger.error("Data Exchange file: [%s] already exists", hdf5_file_name)
            else:
                # Create new folder.
                dirPath = os.path.dirname(hdf5_file_name)
                if not os.path.exists(dirPath):
                    os.makedirs(dirPath)

                # Get the file_name in lower case.
                lFn = hdf5_file_name.lower()

                # Split the string with the delimeter '.'
                end = lFn.split(".")

                # Write the Data Exchange HDF5 file.
                # Open DataExchange file
                f = DataExchangeFile(hdf5_file_name, mode="w")

                self.logger.info("Creating Data Exchange File [%s]", hdf5_file_name)

                # Create core HDF5 dataset in exchange group for projections_theta_range
                # deep stack of x,y images /exchange/data
                self.logger.info("Adding projections to Data Exchange File [%s]", hdf5_file_name)
                f.add_entry(
                    DataExchangeEntry.data(
                        data={"value": data, "units": "counts", "description": "transmission", "axes": axes}
                    )
                )
                #                f.add_entry( DataExchangeEntry.data(data={'value': data, 'units':'counts', 'description': 'transmission', 'axes':'theta:y:x', 'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} }))
                if theta != None:
                    f.add_entry(DataExchangeEntry.data(theta={"value": theta, "units": "degrees"}))
                    self.logger.info("Adding theta to Data Exchange File [%s]", hdf5_file_name)
                else:
                    self.logger.warning("theta is not defined")
                if data_dark != None:
                    self.logger.info("Adding dark fields to  Data Exchange File [%s]", hdf5_file_name)
                    f.add_entry(
                        DataExchangeEntry.data(
                            data_dark={"value": data_dark, "units": "counts", "axes": "theta_dark:y:x"}
                        )
                    )
                #                    f.add_entry( DataExchangeEntry.data(data_dark={'value': data_dark, 'units':'counts', 'axes':'theta_dark:y:x', 'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} }))
                else:
                    self.logger.warning("data dark is not defined")
                if data_white != None:
                    self.logger.info("Adding white fields to  Data Exchange File [%s]", hdf5_file_name)
                    f.add_entry(
                        DataExchangeEntry.data(
                            data_white={"value": data_white, "units": "counts", "axes": "theta_white:y:x"}
                        )
                    )
                #                    f.add_entry( DataExchangeEntry.data(data_white={'value': data_white, 'units':'counts', 'axes':'theta_white:y:x', 'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} }))
                else:
                    self.logger.warning("data white is not defined")
                if data_exchange_type != None:
                    self.logger.info("Adding data type to  Data Exchange File [%s]", hdf5_file_name)
                    f.add_entry(DataExchangeEntry.data(title={"value": data_exchange_type}))

                if source_name != None:
                    f.add_entry(DataExchangeEntry.source(name={"value": source_name}))
                if source_mode != None:
                    f.add_entry(DataExchangeEntry.source(mode={"value": source_mode}))
                if source_datetime != None:
                    f.add_entry(DataExchangeEntry.source(datetime={"value": source_datetime}))

                if beamline != None:
                    f.add_entry(DataExchangeEntry.source(beamline={"value": beamline}))
                if energy != None:
                    f.add_entry(
                        DataExchangeEntry.monochromator(
                            energy={"value": energy, "units": "keV", "dataset_opts": {"dtype": "d"}}
                        )
                    )
                if current != None:
                    f.add_entry(
                        DataExchangeEntry.source(
                            current={"value": current, "units": "mA", "dataset_opts": {"dtype": "d"}}
                        )
                    )

                if actual_pixel_size != None:
                    f.add_entry(
                        DataExchangeEntry.detector(
                            actual_pixel_size_x={
                                "value": actual_pixel_size,
                                "units": "microns",
                                "dataset_opts": {"dtype": "d"},
                            },
                            actual_pixel_size_y={
                                "value": actual_pixel_size,
                                "units": "microns",
                                "dataset_opts": {"dtype": "d"},
                            },
                        )
                    )

                if experimenter_name != None:
                    f.add_entry(DataExchangeEntry.experimenter(name={"value": experimenter_name}))
                if experimenter_affiliation != None:
                    f.add_entry(DataExchangeEntry.experimenter(affiliation={"value": experimenter_affiliation}))
                if experimenter_email != None:
                    f.add_entry(DataExchangeEntry.experimenter(email={"value": experimenter_email}))

                if instrument_comment != None:
                    f.add_entry(DataExchangeEntry.instrument(comment={"value": instrument_comment}))
                if sample_name == None:
                    sample_name = end[0]
                    f.add_entry(
                        DataExchangeEntry.sample(
                            name={"value": sample_name},
                            description={
                                "value": "Sample name assigned by the HDF5 converter and based on the HDF5 file name"
                            },
                        )
                    )
                else:
                    f.add_entry(DataExchangeEntry.sample(name={"value": sample_name}))
                if sample_comment != None:
                    f.add_entry(DataExchangeEntry.sample(comment={"value": sample_comment}))

                if acquisition_mode != None:
                    f.add_entry(DataExchangeEntry.acquisition(mode={"value": acquisition_mode}))
                if acquisition_comment != None:
                    f.add_entry(DataExchangeEntry.acquisition(comment={"value": acquisition_comment}))

                if sample_position_x != None:
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_position_x={
                                "value": sample_position_x,
                                "units": "microns",
                                "dataset_opts": {"dtype": "d"},
                            }
                        )
                    )
                if sample_position_y != None:
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_position_y={
                                "value": sample_position_y,
                                "units": "microns",
                                "dataset_opts": {"dtype": "d"},
                            }
                        )
                    )
                if sample_position_z != None:
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_position_z={
                                "value": sample_position_z,
                                "units": "microns",
                                "dataset_opts": {"dtype": "d"},
                            }
                        )
                    )
                if sample_image_shift_x != None:
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_image_shift_x={
                                "value": sample_image_shift_x,
                                "units": "microns",
                                "dataset_opts": {"dtype": "d"},
                            }
                        )
                    )
                if sample_image_shift_y != None:
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_image_shift_y={
                                "value": sample_image_shift_y,
                                "units": "microns",
                                "dataset_opts": {"dtype": "d"},
                            }
                        )
                    )

                if image_exposure_time != None:
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            image_exposure_time={
                                "value": image_exposure_time,
                                "units": "s",
                                "dataset_opts": {"dtype": "d"},
                            }
                        )
                    )
                if image_time != None:
                    f.add_entry(DataExchangeEntry.acquisition(image_time={"value": image_time}))
                if image_theta != None:
                    f.add_entry(DataExchangeEntry.acquisition(image_theta={"value": image_theta, "units": "degrees"}))
                f.close()
                self.logger.info("DONE!!!!. Created Data Exchange File [%s]", hdf5_file_name)

        else:
            self.logger.warning("Nothing to do ...")
def main():

    ##file_name = '/local/data/databank/SLS_2011/Blakely_SLS/Blakely.tif'
    ##log_file = '/local/data/databank/SLS_2011/Blakely_SLS/Blakely.log'
    ##
    ##hdf5_file_name = '/local/data/databank/dataExchange/microCT/Blakely_SLS_2011.h5'

    file_name = '/local/data/databank/SLS_2011/Hornby_SLS/Hornby_b.tif'
    log_file = '/local/data/databank/SLS_2011/Hornby_SLS/Hornby.log'

    hdf5_file_name = '/local/data/databank/dataExchange/microCT/Hornby_SLS_2011.h5'

    verbose = True

    if verbose: print file_name
    if verbose: print log_file
    if verbose: print hdf5_file_name



    #Read input SLS data
    file = open(log_file, 'r')
    if verbose: print '###############################'
    for line in file:
        if 'Number of darks' in line:
            NumberOfDarks = re.findall(r'\d+', line)
            if verbose: print 'Number of Darks', NumberOfDarks[0]
        if 'Number of flats' in line:
            NumberOfFlats = re.findall(r'\d+', line)
            if verbose: print 'Number of Flats', NumberOfFlats[0]
        if 'Number of projections' in line:
            NumberOfProjections = re.findall(r'\d+', line)
            if verbose: print 'Number of Projections', NumberOfProjections[0]
        if 'Number of inter-flats' in line:
            NumberOfInterFlats = re.findall(r'\d+', line)
            if verbose: print 'Number of inter-flats', NumberOfInterFlats[0]
        if 'Inner scan flag' in line:
            InnerScanFlag = re.findall(r'\d+', line)
            if verbose: print 'Inner scan flag', InnerScanFlag[0]
        if 'Flat frequency' in line:
            FlatFrequency = re.findall(r'\d+', line)
            if verbose: print 'Flat frequency', FlatFrequency[0]
        if 'Rot Y min' in line:
            RotYmin = re.findall(r'\d+.\d+', line)
            if verbose: print 'Rot Y min', RotYmin[0]
        if 'Rot Y max' in line:
            RotYmax = re.findall(r'\d+.\d+', line)
            if verbose: print 'Rot Y max', RotYmax[0]
        if 'Angular step' in line:
            AngularStep = re.findall(r'\d+.\d+', line)
            if verbose: print 'Angular step', AngularStep[0]
    if verbose: print '###############################'
    file.close()

    dark_start = 1
    dark_end = int(NumberOfDarks[0]) + 1
    white_start = dark_end
    white_end = white_start + int(NumberOfFlats[0])
    projections_start = white_end
    projections_end = projections_start + int(NumberOfProjections[0])

    if verbose: print dark_start, dark_end
    if verbose: print white_start, white_end
    if verbose: print projections_start, projections_end

    dark_start = 1
    dark_end = 21
    white_start = 21
    white_end = 221
    projections_start = 221
    projections_end = 1662

    ### if testing uncomment
    ##dark_end = 4
    ##white_end = 24
    ##projections_end = 224

    mydata = Convert()
    # Create minimal hdf5 file
    mydata.series_of_images(file_name,
                     hdf5_file_name,
                     projections_start,
                     projections_end,
                     white_start = white_start,
                     white_end = white_end,
                     dark_start = dark_start,
                     dark_end = dark_end,
                     verbose = False
                     )

     
    # Add extra metadata if available

    # Open DataExchange file
    f = DataExchangeFile(hdf5_file_name, mode='a') 

    # Create HDF5 subgroup
    # /measurement/instrument
    f.add_entry( DataExchangeEntry.instrument(name={'value': 'Tomcat'}) )

    # Create HDF5 subgroup
    # /measurement/instrument/source
    f.add_entry( DataExchangeEntry.source(name={'value': 'Swiss Light Source'},
                                        date_time={'value': "2010-11-08T14:51:56+0100"},
                                        beamline={'value': "Tomcat"},
                                        current={'value': 401.96, 'units': 'mA', 'dataset_opts': {'dtype': 'd'}},
                                        )
    )

    # Create HDF5 subgroup
    # /measurement/instrument/monochromator
    f.add_entry( DataExchangeEntry.monochromator(type={'value': 'Multilayer'},
                                                energy={'value': 19.260, 'units': 'keV', 'dataset_opts': {'dtype': 'd'}},
                                                mono_stripe={'value': 'Ru/C'},
                                                )
        )

    # Create HDF5 subgroup
    # /measurement/experimenter
    f.add_entry( DataExchangeEntry.experimenter(name={'value':"Federica Marone"},
                                                role={'value':"Project PI"},
                                                affiliation={'value':"Swiss Light Source"},
                                                phone={'value':"+41 56 310 5318"},
                                                email={'value':"*****@*****.**"},

                    )
        )

    # Create HDF5 subgroup
    # /measurement/instrument/detector
    f.add_entry( DataExchangeEntry.detector(manufacturer={'value':'CooKe Corporation'},
                                            model={'value': 'pco dimax'},
                                            serial_number={'value': '1234XW2'},
                                            bit_depth={'value': 12, 'dataset_opts':  {'dtype': 'd'}},
                                            x_pixel_size={'value': 6.7e-6, 'dataset_opts':  {'dtype': 'f'}},
                                            y_pixel_size={'value': 6.7e-6, 'dataset_opts':  {'dtype': 'f'}},
                                            x_dimensions={'value': 2048, 'dataset_opts':  {'dtype': 'i'}},
                                            y_dimensions={'value': 2048, 'dataset_opts':  {'dtype': 'i'}},
                                            x_binning={'value': 1, 'dataset_opts':  {'dtype': 'i'}},
                                            y_binning={'value': 1, 'dataset_opts':  {'dtype': 'i'}},
                                            operating_temperature={'value': 270, 'units':'K', 'dataset_opts':  {'dtype': 'f'}},
                                            exposure_time={'value': 170, 'units':'ms', 'dataset_opts':  {'dtype': 'd'}},
                                            frame_rate={'value': 3, 'dataset_opts':  {'dtype': 'i'}},
                                            output_data={'value':'/exchange'}
                                            )
        )

    f.add_entry(DataExchangeEntry.objective(magnification={'value':10, 'dataset_opts': {'dtype': 'd'}},
                                        )
        )

    f.add_entry(DataExchangeEntry.scintillator(name={'value':'LuAg '},
                                                type={'value':'LuAg'},
                                                scintillating_thickness={'value':20e-6, 'dataset_opts': {'dtype': 'd'}},
            )
        )

    # Create HDF5 subgroup
    # /measurement/experiment
    f.add_entry( DataExchangeEntry.experiment( proposal={'value':"e11218"},
                )
        )
    f.close()
    if verbose: print "Done converting ", file_name
Esempio n. 3
0
def pack_data_exchange():
    f = DataExchangeFile(CXP.io.data_exchange_filename, mode='w')
    sim = DataExchangeEntry.simulation(
        name={'value': 'Simulated Ptycho Data.'},
        energy={
            'value': CXP.experiment.energy,
            'units': 'keV'
        },
        focusing_optic={'value': CXP.experiment.optic},
        probe_modes={'value': CXP.reconstruction.probe_modes},
        noise_model={'value': CXP.simulation.noise_model},
        gaussian_noise_level={'value': CXP.simulation.gaussian_noise_level},
        total_photons={'value': CXP.simulation.total_photons},
        beam_stop={'value': CXP.simulation.beam_stop},
        beam_stop_size={'value': CXP.simulation.beam_stop_size},
        beam_stop_attenuation={'value': CXP.simulation.beam_stop_attenuation},
        defocus={'value': CXP.simulation.defocus},
        position_jitter={
            'value': CXP.reconstruction.initial_position_jitter_radius,
            'units': 'pixels'
        })
    f.add_entry(sim)
    sample = DataExchangeEntry.sample(
        root='/simulation',
        name={'value': 'ground truth sample complex amplitude'},
        data={
            'value': cxph.sample.data[0],
            'units': 'sqrt(counts)'
        },
    )
    f.add_entry(sample)
    probe = DataExchangeEntry.sample(
        root='/simulation',
        entry_name='probe',
    )
    for mode in range(CXP.reconstruction.probe_modes):
        setattr(probe, 'mode_{:d}'.format(mode), {
            'value': cxph.input_probe.modes[mode].data[0],
            'units': 'counts'
        })

    f.add_entry(probe)
    detector = DataExchangeEntry.detector(
        root='/simulation',
        x_pixel_size={'value': CXP.experiment.dx_d},
        y_pixel_size={'value': CXP.experiment.dx_d},
        x_dimension={'value': CXP.experiment.px},
        y_dimension={'value': CXP.experiment.py},
        distance={'value': CXP.experiment.z},
        basis_vectors={
            'value': [[0, -CXP.experiment.dx_d, 0],
                      [-CXP.experiment.dx_d, 0, 0]]
        },
        corner_position={'value': [0, 0, 0]})
    f.add_entry(detector)
    data = DataExchangeEntry.data(
        name={'value': 'simulated_data'},
        data={
            'value': sp.array(cxph.det_mod.data),
            'axes': 'translation:y:x',
            'units': 'counts',
            'dataset_opts': {
                'compression': 'gzip',
                'compression_opts': 4
            }
        },
        translation={'value': '/exchange/sample/geometry/translation'})
    f.add_entry(data)
    # Get scan positions into dex format
    pos = sp.zeros((cxph.positions.total, 3))
    y, x = cxph.positions.correct
    for i in range(cxph.positions.total):
        pos[i, 0], pos[i, 1] = x[i] * CXP.dx_s, y[i] * CXP.dx_s

    positions = DataExchangeEntry.translation(
        root='/exchange/sample/geometry',
        name={'value': 'ptychography scan positions'},
        scan_type={'value': CXP.measurement.ptycho_scan_type},
        data={
            'value': pos,
            'units': 'm'
        })

    f.add_entry(positions)
    f.close()
def write_example(filename):

    # --- prepare data ---

    # Generate fake raw data
    rawdata = np.ones(180 * 256 * 256, np.uint16).reshape(180, 256, 256)
    rawdata_white = np.ones(2 * 256 * 256, np.uint16).reshape(2, 256, 256)
    rawdata_dark = np.zeros(10 * 256 * 256, np.uint16).reshape(10, 256, 256)

    # Generate fake normalized data
    normalizeddata = np.ones(180 * 256 * 256, \
                             np.float64).reshape(180, 256, 256)

    # Generate fake reconstructed data
    reconstructeddata = np.ones(256 * 256 * 256, \
                                np.float64).reshape(256, 256, 256)
     
    # x, y and z ranges
    x = np.arange(128)
    y = np.arange(128)
    z = np.arange(180);
    
    # Fabricated theta values
    theta = (z / float(180)) * 180.0
    theta_white = (0.0, 180.0)
    theta_dark = (0.0, 0.0, 0.0, 0.0, 0.0, 180.0, 180.0, 180.0, 180.0, 180.0)

    # Fabricated data_shift_x and data_shift_y value
    data_shift_x = np.random.randint(-100, 100, size=180) 
    data_shift_y = np.random.randint(-100, 100, size=180) 

    # --- create file ---

    print filename
    
    # Open DataExchange file
    f = DataExchangeFile(filename, mode='w') 
        
    
    # Create core HDF5 dataset in exchange group for 180 deep stack
    # of x,y images /exchange/data
    f.add_entry( DataExchangeEntry.data(data={'value': rawdata, 'units':'counts', 'description': 'transmission', 'axes':'theta:y:x',
                                            'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} })
    )
    f.add_entry( DataExchangeEntry.data(title={'value': 'tomography_raw_projections'}))
    f.add_entry( DataExchangeEntry.data(data_dark={'value':rawdata_dark, 'units':'counts', 'axes':'theta_dark:y:x',
                                            'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} })
    )
    f.add_entry( DataExchangeEntry.data(data_white={'value': rawdata_white, 'units':'counts', 'axes':'theta_white:y:x',
                                            'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} })
    )
    f.add_entry( DataExchangeEntry.data(theta={'value': theta, 'units':'degrees'}))
    f.add_entry( DataExchangeEntry.data(theta_dark={'value': theta_dark, 'units':'degrees'}))
    f.add_entry( DataExchangeEntry.data(theta_white={'value': theta_white, 'units':'degrees'}))
    f.add_entry( DataExchangeEntry.data(data_shift_x={'value': data_shift_x}))
    f.add_entry( DataExchangeEntry.data(data_shift_y={'value': data_shift_y}))
                  
    # Exchange HDF5 group
    # /exchange_2
    # this will be the out_put of the normalization process
    f.add_entry( DataExchangeEntry.data(root='exchange_2', title={'value': 'tomography normalized projections'}) )
    f.add_entry( DataExchangeEntry.data(root='exchange_2', data={'value': normalizeddata, 'units':'counts', 'axes':'theta:y:x',
                                            'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} })
    )
    f.add_entry( DataExchangeEntry.data(root='exchange_2', theta={'value': theta, 'units':'degrees'}))

    # Exchange HDF5 group
    # /exchange_3
    # this will be the out_put of the reconstruction process
    f.add_entry( DataExchangeEntry.data(root='exchange_3', title={'value': 'tomography reconstructions'}) )
    f.add_entry( DataExchangeEntry.data(root='exchange_3', data={'value': reconstructeddata, 'units':'density', 'axes':'z:y:x',
                                            'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} })
    )

    # Create HDF5 group measurement
    # /measuremen
    f.add_entry( DataExchangeEntry.instrument(name={'value': 'APS 2-BM'}) )

    # Create HDF5 subgroup
    # /measurement/instrument/source
    f.add_entry( DataExchangeEntry.source(name={'value': 'APS'}, 
                                        date_time={'value': "2012-07-31T21:15:23+0600"},
                                        beamline={'value': "2-BM"}, 
                                        current={'value': 101.199, 'units': 'mA', 'dataset_opts':  {'dtype': 'd'}},
                                        energy={'value': 7.0, 'units':'GeV', 'dataset_opts':  {'dtype': 'd'}},
                                        mode={'value':'TOPUP'}
                                        )
    )
    # Create HDF5 subgroup
    # /measurement/instrument/attenuator           
    f.add_entry( DataExchangeEntry.attenuator(thickness={'value': 1e-3, 'units': 'm', 'dataset_opts':  {'dtype': 'd'}},
                                            type={'value': 'Al'}
                                            )
        )

    # Create HDF5 subgroup
    # /measurement/instrument/monochromator
    f.add_entry( DataExchangeEntry.monochromator(type={'value': 'Multilayer'},
                                                energy={'value': 19.26, 'units': 'keV', 'dataset_opts':  {'dtype': 'd'}},
                                                energy_error={'value': 1e-3, 'units': 'keV', 'dataset_opts':  {'dtype': 'd'}},
                                                mono_stripe={'value': 'Ru/C'},
                                                )
        )                                                                                                                                                                                                                                                                                                                                                                                                         

    # Create HDF5 subgroup
    # /measurement/instrument/detector
    f.add_entry( DataExchangeEntry.detector(manufacturer={'value':'CooKe Corporation'},
                                            model={'value': 'pco dimax'},
                                            serial_number={'value': '1234XW2'},
                                            bit_depth={'value': 12, 'dataset_opts':  {'dtype': 'd'}},
                                            x_pixel_size={'value': 6.7e-6, 'dataset_opts':  {'dtype': 'f'}},
                                            y_pixel_size={'value': 6.7e-6, 'dataset_opts':  {'dtype': 'f'}},
                                            x_dimensions={'value': 2048, 'dataset_opts':  {'dtype': 'i'}},
                                            y_dimensions={'value': 2048, 'dataset_opts':  {'dtype': 'i'}},
                                            x_binning={'value': 1, 'dataset_opts':  {'dtype': 'i'}},
                                            y_binning={'value': 1, 'dataset_opts':  {'dtype': 'i'}},
                                            operating_temperature={'value': 270, 'units':'K', 'dataset_opts':  {'dtype': 'f'}},
                                            exposure_time={'value': 170, 'units':'ms', 'dataset_opts':  {'dtype': 'd'}},
                                            frame_rate={'value': 3, 'dataset_opts':  {'dtype': 'i'}},
                                            output_data={'value':'/exchange'}
                                            )
        )

    f.add_entry( DataExchangeEntry.roi(name={'value':'Center Third'},
                                        x1={'value':256, 'dataset_opts':  {'dtype': 'i'}},
                                        x2={'value':1792, 'dataset_opts':  {'dtype': 'i'}},
                                        y1={'value':256, 'dataset_opts':  {'dtype': 'i'}},
                                        y2={'value':1792, 'dataset_opts':  {'dtype': 'i'}},
                                        )
        )

    f.add_entry(DataExchangeEntry.objective(manufacturer={'value':'Zeiss'},
                                            model={'value':'Plan-NEOFLUAR 1004-072'},
                                            magnification={'value':20, 'dataset_opts':  {'dtype': 'd'}},
                                            numerical_aperture={'value':0.5, 'dataset_opts':  {'dtype': 'd'}},
                                        )
        )

    f.add_entry(DataExchangeEntry.scintillator(manufacturer={'value':'Crytur'},
                                                serial_number={'value':'12'},
                                                name={'value':'YAG polished'},
                                                type={'value':'YAG on YAG'},
                                                scintillating_thickness={'value':5e-6, 'dataset_opts':  {'dtype': 'd'}},
                                                substrate_thickness={'value':1e-4, 'dataset_opts':  {'dtype': 'd'}},
            )
        )


    # Create HDF5 subgroup 
    # /measurement/sample
    f.add_entry( DataExchangeEntry.sample( name={'value':'Hornby_b'},
                                            description={'value':'test sample'},
                                            preparation_date={'value':'2011-07-31T21:15:23+0600'},
                                            chemical_formula={'value':'unknown'},
                                            mass={'value':0.25, 'units':'g', 'dataset_opts':  {'dtype': 'd'}},
                                            enviroment={'value':'air'},
                                            temperature={'value':120.0, 'units':'Celsius', 'dataset_opts':  {'dtype': 'd'}},
                                            temperature_set={'value':130.0, 'units':'Celsius', 'dataset_opts':  {'dtype': 'd'}},
            )
        )

    # Create HDF5 subgroup 
    # /measurement/sample/geometry/translation
    f.add_entry( DataExchangeEntry.translation(root='/measurement/sample/geometry',
                    distances={'value':[0,0,0],'axes':'z:y:x', 'units':'m', 'dataset_opts':  {'dtype': 'd'}}
                    )
        )
    # Create HDF5 subgroup
    # /measurement/experimenter
    f.add_entry( DataExchangeEntry.experimenter(name={'value':"John Doe"},
                                                role={'value':"Project PI"},
                                                affiliation={'value':"University of California, Berkeley"},
                                                address={'value':"EPS UC Berkeley CA 94720 4767 USA"},
                                                phone={'value':"+1 123 456 0000"},
                                                email={'value':"*****@*****.**"},
                                                facility_user_id={'value':"a123456"},

                    )
        )
    

    # Create HDF5 subgroup
    # /measurement/experiment
    f.add_entry( DataExchangeEntry.experiment(  proposal={'value':"1234"},
                                                activity={'value':"e11218"},
                                                safety={'value':"9876"},
                )
        )

    # --- All done ---
    f.close()
    def xtomo_exchange(self,
                       data,
                       data_white=None,
                       data_dark=None,
                       theta=None,
                       data_exchange_type=None,
                       source_name=None,
                       source_mode=None,
                       source_datetime=None,
                       beamline=None,
                       energy=None,
                       current=None,
                       actual_pixel_size=None,
                       experimenter_name=None,
                       experimenter_affiliation=None,
                       experimenter_email=None,
                       instrument_comment=None,
                       sample_name=None,
                       sample_comment=None,
                       acquisition_mode=None,
                       acquisition_comment=None,
                       sample_position_x=None,
                       sample_position_y=None,
                       sample_position_z=None,
                       sample_image_shift_x=None,
                       sample_image_shift_y=None,
                       hdf5_file_name=None,
                       axes='theta:y:x',
                       log='INFO'):
        """ 
        Write 3-D data to a data-exchange file.

        Parameters
                    
        data : ndarray
            3-D X-ray absorption tomography raw data.
            Size of the dimensions should be:
            [projections, slices, pixels].
            
        data_white, data_dark : ndarray, optional
            3-D white-field/dark_field data. Multiple
            projections are stacked together to obtain
            a 3-D matrix. 2nd and 3rd dimensions should
            be the same as data: [shots, slices, pixels].
            
        theta : ndarray, optional
            Data acquisition angles corresponding
            to each projection.

        data_excahnge_type : str, optional
            label defyining the type of data contained in data exchange file
            for raw data tomography data use 'tomography_raw_projections'

        source_name, source_mode, source_datetime : str, optional
            label defining the source name, operation mode and date/time when these values were taken

        beamline : str, optional
            label defining the beamline name
        
        energy, current : float, optional
            X-ray energy and bean current

        actual_pixel_size : float, optional
            pixel size on the sample plane
 
        experimenter_name, experimenter_affiliation, experimenter_email : str, optional
            user name, affiliation and e-mail address

        instrument_comment : str, optional
            instrument comment

        sample_name, sample_comment : str, optional
            sample name and comment
        
        acquisition_mode, acquisition_comment : str, optional
            acquisition mode and comment

        hd5_file_name : str
            Output file.

        Notes
        -----
        If file exists, does nothing
                
        Examples
        
        - Convert tomographic projection series (raw, dark, white)  of tiff in data exchange:
            
            >>> import dataexchange

            >>> file_name = '/local/dataraid/databank/Anka/radios/image_.tif'
            >>> dark_file_name = '/local/dataraid/databank/Anka/darks/image_.tif'
            >>> white_file_name = '/local/dataraid/databank/Anka/flats/image_.tif'

            >>> hdf5_file_name = '/local/dataraid/databank/dataExchange/tmp/Anka.h5'

            >>> projections_start = 0
            >>> projections_end = 3167
            >>> white_start = 0
            >>> white_end = 100
            >>> dark_start = 0
            >>> dark_end = 100

            >>> sample_name = 'Anka'
            >>> 
            >>> # Read raw data
            >>> read = dataexchange.Import()
            >>> data, white, dark, theta = read.xtomo_raw(file_name,
            >>>                                                    projections_start = projections_start,
            >>>                                                    projections_end = projections_end,
            >>>                                                    white_file_name = white_file_name,
            >>>                                                    white_start = white_start,
            >>>                                                    white_end = white_end,
            >>>                                                    dark_file_name = dark_file_name,
            >>>                                                    dark_start = dark_start,
            >>>                                                    dark_end = dark_end,
            >>>                                                    projections_digits = 5,
            >>>                                                    log='INFO'
            >>>                                                    )
            >>>
            >>> # Save data
            >>> write = dataexchange.Export()
            >>> write.xtomo_exchange(data = data,
            >>>                       data_white = white,
            >>>                       data_dark = dark,
            >>>                       theta = theta,
            >>>                       hdf5_file_name = hdf5_file_name,
            >>>                       data_exchange_type = 'tomography_raw_projections',
            >>>                       sample_name = sample_name
            >>>                       )

        """

        if (hdf5_file_name != None):
            if os.path.isfile(hdf5_file_name):
                self.logger.error("Data Exchange file: [%s] already exists",
                                  hdf5_file_name)
            else:
                # Create new folder.
                dirPath = os.path.dirname(hdf5_file_name)
                if not os.path.exists(dirPath):
                    os.makedirs(dirPath)

                # Get the file_name in lower case.
                lFn = hdf5_file_name.lower()

                # Split the string with the delimeter '.'
                end = lFn.split('.')

                # Write the Data Exchange HDF5 file.
                # Open DataExchange file
                f = DataExchangeFile(hdf5_file_name, mode='w')

                self.logger.info("Creating Data Exchange File [%s]",
                                 hdf5_file_name)

                # Create core HDF5 dataset in exchange group for projections_theta_range
                # deep stack of x,y images /exchange/data
                self.logger.info(
                    "Adding projections to Data Exchange File [%s]",
                    hdf5_file_name)
                f.add_entry(
                    DataExchangeEntry.data(
                        data={
                            'value': data,
                            'units': 'counts',
                            'description': 'transmission',
                            'axes': axes
                        }))
                #                f.add_entry( DataExchangeEntry.data(data={'value': data, 'units':'counts', 'description': 'transmission', 'axes':'theta:y:x', 'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} }))
                if (theta != None):
                    f.add_entry(
                        DataExchangeEntry.data(theta={
                            'value': theta,
                            'units': 'degrees'
                        }))
                    self.logger.info("Adding theta to Data Exchange File [%s]",
                                     hdf5_file_name)
                else:
                    self.logger.warning("theta is not defined")
                if (data_dark != None):
                    self.logger.info(
                        "Adding dark fields to  Data Exchange File [%s]",
                        hdf5_file_name)
                    f.add_entry(
                        DataExchangeEntry.data(
                            data_dark={
                                'value': data_dark,
                                'units': 'counts',
                                'axes': 'theta_dark:y:x'
                            }))
#                    f.add_entry( DataExchangeEntry.data(data_dark={'value': data_dark, 'units':'counts', 'axes':'theta_dark:y:x', 'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} }))
                else:
                    self.logger.warning("data dark is not defined")
                if (data_white != None):
                    self.logger.info(
                        "Adding white fields to  Data Exchange File [%s]",
                        hdf5_file_name)
                    f.add_entry(
                        DataExchangeEntry.data(
                            data_white={
                                'value': data_white,
                                'units': 'counts',
                                'axes': 'theta_white:y:x'
                            }))
#                    f.add_entry( DataExchangeEntry.data(data_white={'value': data_white, 'units':'counts', 'axes':'theta_white:y:x', 'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4} }))
                else:
                    self.logger.warning("data white is not defined")
                if (data_exchange_type != None):
                    self.logger.info(
                        "Adding data type to  Data Exchange File [%s]",
                        hdf5_file_name)
                    f.add_entry(
                        DataExchangeEntry.data(
                            title={'value': data_exchange_type}))

                if (source_name != None):
                    f.add_entry(
                        DataExchangeEntry.source(name={'value': source_name}))
                if (source_mode != None):
                    f.add_entry(
                        DataExchangeEntry.source(mode={'value': source_mode}))
                if (source_datetime != None):
                    f.add_entry(
                        DataExchangeEntry.source(
                            datetime={'value': source_datetime}))

                if (beamline != None):
                    f.add_entry(
                        DataExchangeEntry.source(beamline={'value': beamline}))
                if (energy != None):
                    f.add_entry(
                        DataExchangeEntry.monochromator(
                            energy={
                                'value': energy,
                                'units': 'keV',
                                'dataset_opts': {
                                    'dtype': 'd'
                                }
                            }))
                if (current != None):
                    f.add_entry(
                        DataExchangeEntry.source(
                            current={
                                'value': current,
                                'units': 'mA',
                                'dataset_opts': {
                                    'dtype': 'd'
                                }
                            }))

                if (actual_pixel_size != None):
                    f.add_entry(
                        DataExchangeEntry.detector(actual_pixel_size_x={
                            'value': actual_pixel_size,
                            'units': 'microns',
                            'dataset_opts': {
                                'dtype': 'd'
                            }
                        },
                                                   actual_pixel_size_y={
                                                       'value':
                                                       actual_pixel_size,
                                                       'units': 'microns',
                                                       'dataset_opts': {
                                                           'dtype': 'd'
                                                       }
                                                   }))

                if (experimenter_name != None):
                    f.add_entry(
                        DataExchangeEntry.experimenter(
                            name={'value': experimenter_name}))
                if (experimenter_affiliation != None):
                    f.add_entry(
                        DataExchangeEntry.experimenter(
                            affiliation={'value': experimenter_affiliation}))
                if (experimenter_email != None):
                    f.add_entry(
                        DataExchangeEntry.experimenter(
                            email={'value': experimenter_email}))

                if (instrument_comment != None):
                    f.add_entry(
                        DataExchangeEntry.instrument(
                            comment={'value': instrument_comment}))
                if (sample_name == None):
                    sample_name = end[0]
                    f.add_entry(
                        DataExchangeEntry.sample(
                            name={'value': sample_name},
                            description={
                                'value':
                                'Sample name assigned by the HDF5 converter and based on the HDF5 file name'
                            }))
                else:
                    f.add_entry(
                        DataExchangeEntry.sample(name={'value': sample_name}))
                if (sample_comment != None):
                    f.add_entry(
                        DataExchangeEntry.sample(
                            comment={'value': sample_comment}))

                if (acquisition_mode != None):
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            mode={'value': acquisition_mode}))
                if (acquisition_comment != None):
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            comment={'value': acquisition_comment}))

                if (sample_position_x != None):
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_position_x={
                                'value': sample_position_x,
                                'units': 'microns',
                                'dataset_opts': {
                                    'dtype': 'd'
                                }
                            }))
                if (sample_position_y != None):
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_position_y={
                                'value': sample_position_y,
                                'units': 'microns',
                                'dataset_opts': {
                                    'dtype': 'd'
                                }
                            }))
                if (sample_position_z != None):
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_position_z={
                                'value': sample_position_z,
                                'units': 'microns',
                                'dataset_opts': {
                                    'dtype': 'd'
                                }
                            }))

                if (sample_image_shift_x != None):
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_image_shift_x={
                                'value': sample_image_shift_x,
                                'units': 'microns',
                                'dataset_opts': {
                                    'dtype': 'd'
                                }
                            }))
                if (sample_image_shift_y != None):
                    f.add_entry(
                        DataExchangeEntry.acquisition(
                            sample_image_shift_y={
                                'value': sample_image_shift_y,
                                'units': 'microns',
                                'dataset_opts': {
                                    'dtype': 'd'
                                }
                            }))

                f.close()
                self.logger.info("DONE!!!!. Created Data Exchange File [%s]",
                                 hdf5_file_name)

        else:
            self.logger.warning("Nothing to do ...")
Esempio n. 6
0
def pack_data_exchange():
    f = DataExchangeFile(CXP.io.data_exchange_filename, mode='w')
    sim = DataExchangeEntry.simulation(
                                        name={'value': 'Simulated Ptycho Data.'},
                                        energy={'value': CXP.experiment.energy, 'units':'keV'},
                                        focusing_optic={'value': CXP.experiment.optic},
                                        probe_modes={'value':CXP.reconstruction.probe_modes},
                                        noise_model={'value': CXP.simulation.noise_model},
                                        gaussian_noise_level={'value': CXP.simulation.gaussian_noise_level},
                                        total_photons={'value': CXP.simulation.total_photons},
                                        beam_stop={'value': CXP.simulation.beam_stop},
                                        beam_stop_size={'value':CXP.simulation.beam_stop_size},
                                        beam_stop_attenuation={'value':CXP.simulation.beam_stop_attenuation},
                                        defocus = {'value':CXP.simulation.defocus},
                                        position_jitter={'value': CXP.reconstruction.initial_position_jitter_radius, 'units':'pixels'}
        )
    f.add_entry(sim)
    sample = DataExchangeEntry.sample(
                                            root='/simulation',
                                            name={'value':'ground truth sample complex amplitude'}, 
                                            data={'value': cxph.sample.data[0], 'units':'sqrt(counts)'},
        )
    f.add_entry(sample)
    probe = DataExchangeEntry.sample(
                                            root='/simulation',
                                            entry_name='probe',
        )
    for mode in range(CXP.reconstruction.probe_modes):
        setattr(probe, 'mode_{:d}'.format(mode), {'value': cxph.input_probe.modes[mode].data[0], 'units':'counts'})

    f.add_entry(probe)
    detector = DataExchangeEntry.detector(
                                            root='/simulation',
                                            x_pixel_size={'value': CXP.experiment.dx_d},
                                            y_pixel_size={'value': CXP.experiment.dx_d},
                                            x_dimension={'value': CXP.experiment.px},
                                            y_dimension={'value': CXP.experiment.py},
                                            distance={'value': CXP.experiment.z},
                                            basis_vectors={'value': [[0,-CXP.experiment.dx_d,0],[-CXP.experiment.dx_d,0,0]]},
                                            corner_position={'value': [0,0,0]}
        )
    f.add_entry(detector)
    data = DataExchangeEntry.data(
                                            name={'value': 'simulated_data'},
                                            data={'value': sp.array(cxph.det_mod.data), 'axes':'translation:y:x', 'units':'counts',
                                            'dataset_opts':  {'compression': 'gzip', 'compression_opts': 4}},
                                            translation={'value':'/exchange/sample/geometry/translation'}          
                                )
    f.add_entry(data)
    # Get scan positions into dex format
    pos = sp.zeros((cxph.positions.total, 3))
    y, x = cxph.positions.correct
    for i in range(cxph.positions.total):
        pos[i,0], pos[i, 1] = x[i]*CXP.dx_s, y[i]*CXP.dx_s

    positions = DataExchangeEntry.translation(
                                            root='/exchange/sample/geometry',
                                            name={'value':'ptychography scan positions'},
                                            scan_type={'value': CXP.measurement.ptycho_scan_type},
                                            data={'value': pos, 'units': 'm'}
                                )

    
    f.add_entry(positions)
    f.close()