ImageD11.forward_model.forward_projector module#

ImageD11.forward_model.forward_projector.K1_calc()#

calculate square of Thomson scattering lenth r0^2, [mm^2] K1 = 7.940788332083948e-24 [mm^2]

ImageD11.forward_model.forward_projector.assemble_sparsefiles(sparsefiles_folder, dtys, outname_sparse='fwd_sparse.h5', image_size=(2162, 2068))#

assemble sparsefiles from each dty position to a single sparse file adapted from “harvest_masterfile” in ImageD11.sinograms.assemble_label

Parameters:
  • sparsefiles_folder (str) – folder holds individual dty sparse files

  • dtys (array) – a list of dty positions [um]

  • outname_sparse (str) – sparse file to write

  • image_size (int array) – dimensions of the 2D projection image

Returns:

sparse file to write

Return type:

outname_sparse (str)

class ImageD11.forward_model.forward_projector.beam(Lss=0.0, FWHM=[0.001, 0.001], energy=43.56, propagation_direction=[1, 0, 0], bandwidth=0.001, polarization=[0, 0.95, 0], flux=500000000000000.0, beam_profile='gaussian', cutoff=0.1)#

Bases: object

Beam class to define X-ray beam size, source-to-sample distance, wavelength, bandwidth and profile Possible to create parallel box-beam, cone beam or pencil beam with different combinations example: ss = beam(Lss = 0, FWHM = [0.001, 0.001], energy = 43.56) # pencil beam 0.001*0.001 mm^2 ss = beam(Lss = 97e3, FWHM = [0.5, 0.2], energy = 43.56) # parallel box beam 0.5*0.2 mm^2 ss = beam(Lss = 10, FWHM = [0.001, 0.001], energy = 43.56) # cone beam 0.001*0.001 mm^2

gaussian(x)#

Gaussian function for describing the beam profile, transformed to weights as a function of distance to the ray center. :param x: distances, e.g. x = np.arange(0, 5, 20) :type x: array

Returns:

intensities (array)

lorentzian(x)#

Lorentzian function for describing the beam profile, translated to weights as a function of distance. :param x: distances, e.g. x = np.arange(0, 5, 50) :type x: array

Returns:

intensities (array)

pseudo_voigt(x, frac=0.5)#

Pseudo-Voigt function (combination of Gaussian and Lorentzian). :param x: distances, e.g. x = np.arange(0, 5, 50) :type x: array :param frac: fraction of lorentzian part :type frac: float

Returns:

intensities (array)

set_beam_shape(plot_flag=False)#

beam shape is used as weights for scaling the voxel contribution as a function of its distance to the ray center and source intensity scaling factor, i.e. two effects Gaussian, Lorentzian and pseudo_voigt profiles are available

set_beam_spectrum(plot_flag=False)#

set beam spectrum by considering the bandwidth NOTE: this has not been considered in the forward computation yet

update()#

Update beam class properties

ImageD11.forward_model.forward_projector.cellvolume(latticepar)#

calculate unit cell volume [angstrom^3]

ImageD11.forward_model.forward_projector.clean_frms(nnz, row, col, val, opts_seg)#

Adapted from “clean” in ImageD11.sinograms.lima_segmenter

ImageD11.forward_model.forward_projector.compute_intersections_single_thread(ray_path, voxel_indices, tol_distances, weights, voxel_size)#

sub-function for intersected_voxels_3d

ImageD11.forward_model.forward_projector.ensure_2d_array(target_hkls)#

Ensures the input target_hkls is a 2D array.

Parameters:

target_hkls (list or array) – A single 1D array or a list of N x 3 arrays.

Returns:

A 2D list of N x 3 arrays.

Return type:

list

ImageD11.forward_model.forward_projector.find_ds_for_multiple_targets(Ahkls, target_hkls)#

Find the ds for a list of target hkls in the list Ahkls.

Parameters:
  • Ahkls (list) – A list of [structure_factor, hkl], e.g. Ahkls = ucell.gethkls(ds_max)

  • target_hkls (list) – a list of target hkl to search for, e.g. [[0, -2, 2], [0, 2, -2]]

Returns:

A list of ds values for each target hkl (or 0 if not found).

Return type:

list

ImageD11.forward_model.forward_projector.forward_peaks_voxels(beam, sample, omega_angles, ucell, pars, dty=0.0, mask=None, ds_max=1.2, exp_time=0.002, plot_peaks=False, verbose=1, use_cluster=False, **kwargs)#

Forward calculating the expected peaks on the peaks for a given beam and sample For a given dty and beam size, first computed the list of intersected sample voxels with the ray; Then, computed the possible peaks on the detector for each voxel Suitable for both s3DXRD and box-beam 3DXRD

Benchmark shows that this parallelized version is 11.4 times faster than non-parallelized version: 360 projs -> 16 s, 24 s with new beam profile 720 projs -> 40 s, 60 s with new beam profile 3600 projs -> 180 s, 312 s with new beam profile

Parameters:
  • beam (class) – beam class defining the beam properties

  • sample (class) – sample class defining the sample properties

  • omega_angles (array) – rotation angles sorted from small to big [deg]

  • ucell (object) – ImageD11.unitcell.unitcell object, e.g. ucell = ImageD11.unitcell.unitcell([4.04761405231186, 4.04761405231186, 4.04761405231186, 90.0, 90.0, 90.0], 225)

  • pars (objected) – ImageD11.parameters object, e.g. pars = ImageD11.parameters.read_par_file(‘/data/visitor/ma6288/id11/20241119/PROCESSED_DATA/nscope_pars/pars.json’)

  • dty (float) – rotation axis position, dty [um]

  • mask (3D array) – mask of sample effective voxels

  • ds_max (float) – maximum 1/d

  • exp_time (float) – exposure time [s]

  • plot_peaks (logic) – flag for plotting peaks

  • **kwargs

  • y0_offset (float) – offset value of the sample when dty = 0, [um]

  • weight (array) – weights of considering fractional contribution of the voxel for scaled to the distance-to-ray-center, determined by the beam FWHM and profile

  • weight_pos (array) – distances corresponding to the weights, scaled by beam FHWM

  • plot_flag (logic) – plot or not for intersected voxels

  • detector (string) – detector name, ‘eiger’ by default

Returns:

forward peaks expected on the detector

Return type:

results

class ImageD11.forward_model.forward_projector.forward_projector(sample_filename, pars_filename, phase_name, output_folder=None, gids_mask=None, verbose=1, auto_set=True, detector_mask=None, to_sparse=False, read_fwd_peaks_from_file=True, **kwargs)#

Bases: object

forward_projector class to compute forward diffraction patterns for a given X-ray beam illuminating a sample

check_halfy()#
generate_slurm_script(script_name='fwd_projector_slurm.sh')#

Generate a SLURM submission script to run run_series_dty with grouped dty values.

Parameters:

script_name (str) – Name of the SLURM script file.

Returns:

Path to the generated SLURM script.

Return type:

str

get_cf(dtys=None)#

gather peaks from file for a given list of dty values and convert them to cf object using ImageD11.sinograms.dataset.colfile_from_dict by default, gather all peaks from all the files existing in the self.output_folder

get_cf_4d(source='3d', factor=50)#

merge 2D/3D peaks to 4D by merging dty source = ‘2d’ or ‘3d’

plot_cf(cf_type='2d', m=None)#

plot the sinogram of cf peaks, i.e. dty vs omega colored by peak intensity m is a boolen mask

read_cf()#

read peaks from h5 file, using ImageD11.columnfile.colfile_from_hdf

run_all()#

run all dty positions with forward projection either on cluster or on local machine

run_series_dty(dtys=None)#

run multiple dty positions with forward projection :param dty: None means run all the dty positions in the class :type dty: None or list

run_single_dty(dty=0.0)#

run single dty forward projection computing time: ~12 s for computing fwd_peaks and ~25 s for segmenting and generating peak sparse file for 3620 omega angles for 361*361 grain map

set_acquisition()#

set acquisition parameters: omega angles and dty range for scanning 3DXRD or box-beam 3DXRD

set_all()#

set all the inputs for the projector: beam, sample, pars, mask and acquisition.

set_beam()#

set the X-ray beam source, including beam energy, FWHM, flux, shape, source-to-sample distance, name etc.

set_dty(scanning_mode=True)#

set dty range for data collection

set_image_size()#

set image size for the projection images

set_opts_seg(bg=None, cut=1, pixels_in_spot=1)#

set segmentation parameters

set_pars()#

set the parameter file.

set_sample()#

set the sample properties: including the grain map, voxel size, density, mass absorption.

set_sample_mask()#

set sample mask for computation by grain IDs (gids_mas) :param gids: a list of grain IDs for making the mask, i.e. only these grains are considered for computation :type gids: list

write_cf()#

write 2D, 3D and 4D peaks to h5 file, using ImageD11.columnfile.colfile_to_hdf

ImageD11.forward_model.forward_projector.get_ImageD11_code_path()#

get the code path of ImageD11

ImageD11.forward_model.forward_projector.get_opts_seg(mask=None, bg=None, cut=1, pixels_in_spot=1)#

set segmentation parameters :param mask: mask for the detector :type mask: 2D array :param bg: background for the detector :type bg: 2D array :param cut: keep values abuve cut in first look at image :type cut: float :param pixels_in_spot: minimum number of pixels in a single spot

ImageD11.forward_model.forward_projector.intersected_sample_pos(mask, dty=0.0, y0_offset=0.0, voxel_size=[1.0, 1.0, 1.0], omega=0.0, ray_size=1.0, weight=[1.0, 0.8, 0.5, 0.13], weight_pos=[0.5, 1.0, 1.5, 2.3], plot_flag=False, detector='eiger')#

Given a dty and a sample rotation angle omega, compute a list of voxels intersected with the X-ray beam and convert them to both sample and lab positions In lab system, the sample rotates by omega, corresponding to rotating the incoming X-ray source by -omega without rotating the sample. This has the benefit to keep the sample mask shape constant throughout the whole calculation Note that all the calculations are based on the sample coordinate system and do conversions after

Parameters:
  • mask (3D array) – sample (or grain) mask Nx*Ny*Nz, note that sample axis normally follow Z, Y, X, so permute the axis may be required

  • dty (float) – horizontal distance between rotation axis and X-ray beam [um]

  • y0_offset (float) – offset of y0, if dty = 0 going through the sample center, then y0_offset = 0 [um]

  • size (voxel) – voxel size in x, y, z axis [um]

  • omega (float) – sample rotation angle [deg]

  • ray_size (float) – FWHM of the incoming X-ray beam [um]

  • weight (array) – weights of considering fractional contribution of the voxel for scaled to the distance-to-ray-center, determined by the beam FWHM and profile

  • weight_pos (array) – distances corresponding to the weights, scaled by beam FHWM

  • plot_flag (logic) – plotting flag

  • detector (string) – name of the detector, eiger or frelon related to the flip story of the detector

Returns:

intersected positions of the sample voxels in sample coordinate system after shifting by dty+y0_offset [x y z] [mm] intersected_labpos: intersected positions of the sample voxels in lab coordinate system [x y z] [mm] intersected_voxels: intersected voxels follow [x y z]

Return type:

intersected_sampos

ImageD11.forward_model.forward_projector.intersected_voxels_3d(grid_size, ray_origin, ray_direction, voxel_size=[1.0, 1.0, 1.0], ray_size=1.0, weight=[1.0, 0.8, 0.5, 0.13], weight_pos=[0.5, 1.0, 1.5, 2.3], mask=None, plot_flag=False)#

Calculate and visualize the intersected voxels for a given ray in 3D.

Parameters:
  • grid_size (tuple) – Dimensions of the grid (Nx, Ny, Nz).

  • ray_origin (array) – Origin of the ray [x, y, z].

  • ray_direction (array) – Direction of the ray [dx, dy, dz].

  • voxel_size (array) – voxel size of the grain map [um/pixel]

  • ray_size (float) – FWHM of the ray [um]

  • weight (array) – weights of considering fractional contribution of the voxel for scaled to the distance-to-ray-center, determined by the beam FWHM and profile

  • weight_pos (array) – distances corresponding to the weights, scaled by beam FHWM

  • mask (array) – 0 and 1 values, 1 corresponds to activated sample voxels

  • plot_flag (logic) – to plot or not.

Returns:

List of intersected voxel coordinates [x, y, z].

Return type:

intersected (list)

ImageD11.forward_model.forward_projector.make_intensity_map(x_positions, y_positions, intensities, x_range=None, y_range=None, pixel_size=0.001, plot_flag=True, cmap='viridis')#

Generate and plot an intensity map based on input x, y positions and the associated intensities.

Parameters:
  • x_positions (array) – x positions

  • y_positions (array) – y positions

  • intensities (array) – intensities

  • x_range (float) – min and max x range values

  • y_range (float) – min and max y range values

  • pixel_size (float) – pixel size for generating the image

  • plot_flag (logic) – for making a plot

  • cmap (str) – color map for plotting

Returns:

intensity_map

ImageD11.forward_model.forward_projector.make_one_projection_with_psf(fwd_peaks, rot_angle, rot_step=0.05, image_size=(2162, 2068), detector='eiger', int_factors=(0.1065, 0.7807, 0.1065))#

Create one single projection image from position and intensity data with a point spread function (psf). Instead of directly applying psf on 3D image, we decompose the psf to 2D-filters across the neiboring projections: for psf_sigma = [1.0, 1.0, 0.5], psf [omega -] = [[0.008, 0.0132, 0.008], [0.0132, 0.0217, 0.0132],[0.008, 0.0132, 0.008]] intensity fraction: 0.1065 psf [omega] = [[0.0591, 0.0975, 0.0591],[0.0975, 0.1607, 0.0975, 0.0591, 0.0975, 0.0591]] intensity fraction: 0.7870 psf [omega +] = [[0.008, 0.0132, 0.008], [0.0132, 0.0217, 0.0132],[0.008, 0.0132, 0.008]] intensity fraction: 0.1065 So, we directly distribute the sum_intensity over 3 frames across omega-, omega and omega+, corresponding to [0.1065, 0.7870, 0.1065] of the sum_intensity, while the shape of the filter can be remained as the same, i.e. Gaussian filter with a sigma of 1

Parameters:
  • fwd_peaks (numpy array) – forward computed peaks N*24 array

  • rot_angle (float) – the ideal rotation angle corresponding to the projection no.

  • rot_step (float) – step size of the omega rotation [deg]

  • image_size (tuple) – size of the output image (rows, cols)

  • detector (string) – detector name, “eiger” or “frelon”

  • int_factors (tuple) – intensity distribution factors for projection left, middle and right across rotation angles

Returns:

generated projection [x, y]

Return type:

image

One projection takes about 0.005 seconds

TODO: psf should also depend on the incident angle between the diffracted beam and the detector plane, i.e. more extended along radial direction

ImageD11.forward_model.forward_projector.make_projections_with_psf(fwd_peaks, omega_angles, image_size=(2162, 2068), detector='eiger', int_factors=(0.1065, 0.7807, 0.1065), sum_flag=False)#

Make a series of projection images across different rotation angles for one rotation considering point spread function (psf).

Parameters:
  • fwd_peaks (numpy array) – Forward computed peaks N*24 array.

  • omega_angles (numpy array) – List of rotation angles for projections. [deg]

  • image_size (tuple) – Size of the output image (rows, cols).

  • detector (string) – Detector name, “eiger” or “frelon”.

  • int_factors (tuple) – Intensity distribution factors for projection left, middle and right across rotation angles.

Returns:

a 3D array containing projection images [num_angles, rows, cols]. projs_sum: a 2D array summing up all the projections along rotation angle

Return type:

projs (array)

3620 projections takes about 91 seconds

ImageD11.forward_model.forward_projector.make_projs_and_sparse_file(fwd_peaks, destname, omega_angles, opts_seg, detector='eiger', detector_mask=None, image_size=(2162, 2068), int_factors=(0.1065, 0.7807, 0.1065))#

Make projection image and do segmentation on it to generate sparse peaks h5 file Combine make_one_projection_with_psf and adaptation of “segment_lima” in ImageD11.sinograms.lima_segmenter The advantage with this is processing frame by frame, instead of producing a series of frames and then doing sementation (slower and more memory consuming) :param fwd_peaks: Forward computed peaks N*24 array. :type fwd_peaks: numpy array :param dsetname: output filename :type dsetname: str :param omega_angles: List of rotation angles for projections. [deg] :type omega_angles: numpy array :param opts_seg: segmenting options, e.g.: :type opts_seg: dict :param opts_seg = {“mask”: None,

“bg”: None, “cut”: 1, # keep values abuve cut in first look at image “overwrite”: False, “howmany”: 100000, # max pixels per frame to keep “thresholds”: 55, “pixels_in_spot”: 1}

Parameters:
  • detector (str) – detector name, e.g. “eiger” or “frelon3”

  • detector_mask (2D array) – detector mask image, 1-active, 0-non-active

  • image_size (int array) – dimensions of the 2D projection image

  • int_factors (tuple) – Intensity distribution factors for projection left, middle and right across rotation angles.

Returns:

output filename with saved sparse peaks

Return type:

dsetname (str)

ImageD11.forward_model.forward_projector.merge_rows(data, columns_to_cluster=[0, 9, 12, 13, 14], epsilons=[0.1, 2, 0.1, 0.1, 0.1], special_col_index=23, weighted_avg=True, min_samples=1)#

Merge rows based on proximity of specific columns with column-specific epsilon values. The default values are suitable for fwd_peaks, where columns_to_cluster=[0, 9, 12, 13, 14, 18, 19] correspond to grainID, rot, hkl, dety_pixel(fc), detz_pixel(sc)

Parameters:
  • data (ndarray) – Input array with shape (n_rows, n_cols).

  • columns_to_cluster (list) – Indices of columns to check for closeness.

  • epsilons (list) – List of epsilon values for each column in columns_to_cluster.

  • special_col_index (int) – Index of the special column to sum instead of averaging.

  • weighted_avg (bool) – Whether to use weighted averaging (weights from a specific column).

  • min_samples (int) – Minimum samples to form a cluster.

Returns:

Array with merged rows. clusters: cluster ID

Return type:

ndarray

ImageD11.forward_model.forward_projector.plot_fwd_peaks(fwd_peaks)#
ImageD11.forward_model.forward_projector.process_omega(omega, mask, DS, beam, sample, pars, ucell, rot_step, ds_max, Lsam2det, args, verbose)#

sub-function for processing one omega angle for forward_peaks_voxels

ImageD11.forward_model.forward_projector.reader_frms(frms, mask, opts_seg, start=0)#

Adapted from “reader” in ImageD11.sinograms.lima_segmenter iterator to read frames and segment them returns sparseframes

Parameters:
  • frms (3D array) – projections to be segmented

  • mask (2D array) – mask image for the detector

  • opts_seg (dict) – segmenting options, e.g.:

  • {"mask" (opts_seg =) – None, “bg”: None, “cut”: 1, # keep values abuve cut in first look at image “overwrite”: False, “howmany”: 100000, # max pixels per frame to keep “thresholds”: 55, “pixels_in_spot”: 1}

  • start (int) – first indice for projections to be segmented

Returns:

output filename

Return type:

dsetname (str)

class ImageD11.forward_model.forward_projector.sample(filename=None, outname=None, min_misori=3, crystal_system='cubic', dis_tol=np.float64(1.7320508075688772), remove_small_grains=True, min_vol=3)#

Bases: object

Sample class to define the sample illuminated by the X-ray beam It can be obtained from experimentally reconstructed sample (available for now) or virtually created sample (TODO)

get_Rsample()#

get sample radius by assuming a cylinder-like sample shape from the grain map dimensions [mm]

read_DS()#
read_grainmap()#
read_tensormap()#
set_mass_abs(mass_abs=0.5685)#

set mass-energy absorption coefficient [cm^2/g]

set_rou(rou=2.7)#

set sample density [g/cm^3]

write_DS()#

write DS to an h5 file with filename defined as self.outname’

ImageD11.forward_model.forward_projector.segment_frms(frms, destname, opts_seg, detector='eiger')#

Adapted from “segment_lima” in ImageD11.sinograms.lima_segmenter Does segmentation on a series of frames, e.g. generated from fwd_peaks Modified based on the function segment_lima in ImageD11/sinograms/lima_segmenter.py :param frms: projections generated from fwd_peaks using forward_projector.make_projections_with_psf :type frms: 3D array :param dsetname: output filename :type dsetname: str :param detector: detector name, e.g. “eiger” or “frelon3” :type detector: str :param opts_seg: segmenting options, e.g.: :type opts_seg: dict :param opts_seg = {“mask”: None,

“bg”: None, “cut”: 1, # keep values abuve cut in first look at image “overwrite”: False, “howmany”: 100000, # max pixels per frame to keep “thresholds”: 55, “pixels_in_spot”: 1}

Returns:

output filename

Return type:

dsetname (str)

ImageD11.forward_model.forward_projector.set_tmp_dir(tmp_dir='/tmp_14_days/slurm/log')#

set a temporary directory for multiprocessing to a writable location