/*******************************************************************************
*
* McXtrace, x-ray tracing package
*         Copyright, All rights reserved
*         DTU Physics, Kgs. Lyngby, Denmark
*         Synchrotron SOLEIL, Saint-Aubin, France
*
* Component: Grating_trans
*
* %Identification
*
* Written by: Erik B Knudsen (erkn@fysik.dtu.dk) 
* Date: December 2016
* Version: 1.0
* Release: McXtrace 1.4
* Origin: DTU Physics
*
* Transmission grating
*
* %Description
* Model of a 1D rectangular transmission grating based on the theory developed in Schnopper et. al., Applied Optics, 1977.
* The grating lines are assumed to be vertical. Within each period a fraction gamma is the "open" fraction. 
* (I.e. 1 is completely open). At present only absorption in the substrate (modelled by the thickness sdepth) 
* is included.
*
* Phase shifts of the diffracted orders are not modelled (phi is unchanged).
*
* This component can benefit from SPLITing.
*
* Example: Grating_trans(
*   xwidth=25e-3, yheight=25e-3, gamma=0.4, period=2000e-10, zdepth=5100e-10, max_order=3, material="Au.txt")
*
* %Parameters
* Input parameters:
* period:     [m]   Distance between grating grooves.
* zdepth:     [m]   Depth of grooves.
* gamma:      [0-1] Open fraction of the period (duty cycle). 1 means fully open.
* sdepth:     [m]   Thickness of substrate. The default is to have no substrate - i.e. rods. 
* xwidth:     [m]   Width of the grating. Defines how many lines there are in total.
* yheight:    [m]   Height of the grating.
* material:   [str] Data file (NIST format, mu/rho in column 5, 0-based) of the material from which the grating is made.
* substrate:  [str] Data file (NIST format, mu/rho in column 5, 0-based) with material data for the substrate.
* fixed_delta:[1]   Set delta to the given constant (0 = use tabulated value). Useful for debugging.
* max_order:  [1]   Maximum order to diffract
* 
* %End
*******************************************************************************/

DEFINE COMPONENT Grating_trans
SETTING PARAMETERS (xwidth=1e-3, yheight=1e-3, period=1e-6,gamma=0.5,zdepth=1e-6,sdepth=0, string material="Au.txt",
      string substrate="",int max_order=2,double fixed_delta=0)

SHARE
%{
  %include "read_table-lib"
%}


DECLARE
%{
  int Z;
  int mu_c;
  double Ar;
  double rho;
  double delta_prefactor;
  t_Table table;
  double srho;
  int smu_c;
  t_Table stable;
%}



INITIALIZE
%{
  int status;

  srho = 0;
  smu_c = 0;

  if (xwidth == 0 || yheight == 0) {
    fprintf (stderr, "Error (%s): Grating has 0 area.\n", NAME_CURRENT_COMP);
    exit (-1);
  }
  if (zdepth <= 0) {
    fprintf (stderr, "Error (%s): zdepth must be > 0.\n", NAME_CURRENT_COMP);
    exit (-1);
  }
  if (period <= 0) {
    fprintf (stderr, "Error (%s): period must be > 0.\n", NAME_CURRENT_COMP);
    exit (-1);
  }
  if (gamma <= 0 || gamma > 1) {
    fprintf (stderr, "Error (%s): gamma must be in ]0,1].\n", NAME_CURRENT_COMP);
    exit (-1);
  }
  if (max_order < 0) {
    fprintf (stderr, "Error (%s): max_order must be >= 0.\n", NAME_CURRENT_COMP);
    exit (-1);
  }
  if (sdepth < 0) {
    fprintf (stderr, "Error (%s): sdepth must be >= 0.\n", NAME_CURRENT_COMP);
    exit (-1);
  }

  /*check if material datafiles are present - if so load them*/
  if ((status = Table_Read (&(table), material, 0)) == -1) {
    fprintf (stderr, "Error: Could not parse file \"%s\" in COMP %s\n", material, NAME_CURRENT_COMP);
    exit (-1);
  }
  char** header_parsed;
  header_parsed = Table_ParseHeader (table.header, "Z", "A[r]", "rho", "Z/A", "sigma[a]", NULL);
  if (header_parsed[0]) {
    Z = strtol (header_parsed[0], NULL, 10);
  }
  if (header_parsed[1]) {
    Ar = strtod (header_parsed[1], NULL);
  }
  if (!header_parsed[1] || Ar <= 0) {
    fprintf (stderr, "Error(%s): A[r] missing or invalid in header of %s.\n", NAME_CURRENT_COMP, material);
    exit (-1);
  }
  if (header_parsed[2]) {
    rho = strtod (header_parsed[2], NULL);
  } else {
    fprintf (stderr, "Warning(%s): %s not found in header of %s, set to 1\n", NAME_CURRENT_COMP, "rho", material);
    rho = 1;
  }
  /*NIST format: mu/rho is in column 5 (0-based)*/
  mu_c = 5;
  if (table.columns <= mu_c) {
    fprintf (stderr, "Error(%s): %s has %d columns, NIST format with at least %d columns required.\n", NAME_CURRENT_COMP, material, (int)table.columns, mu_c + 1);
    exit (-1);
  }

  delta_prefactor = NA * (rho * 1e-24) / Ar * 2.0 * M_PI * RE;

  /*read substrate datafile if present*/
  if (substrate && strlen (substrate)) {
    if ((status = Table_Read (&(stable), substrate, 0)) == -1) {
      fprintf (stderr, "Error(%s): Could not parse file \"%s\".\n", NAME_CURRENT_COMP, substrate);
      exit (-1);
    }
    header_parsed = Table_ParseHeader (stable.header, "Z", "A[r]", "rho", "Z/A", "sigma[a]", NULL);
    if (header_parsed[2]) {
      srho = strtod (header_parsed[2], NULL);
    }
    if (!header_parsed[2] || srho <= 0) {
      fprintf (stderr, "Error(%s): rho missing or invalid in header of %s.\n", NAME_CURRENT_COMP, substrate);
      exit (-1);
    }

    smu_c = 5;
    if (stable.columns <= smu_c) {
      fprintf (stderr, "Error(%s): %s has %d columns, NIST format with at least %d columns required.\n", NAME_CURRENT_COMP, substrate, (int)stable.columns, smu_c + 1);
      exit (-1);
    }
  }
%}


TRACE
%{
  double e, k, f, delta, beta, mu0, smu0, order_factor, order_likelihood;
  double zdepth_eff, sec, dkx, tot, kxn, kzn, cx, cy, cz;
  int m;
  int order;

  PROP_Z0;
  if (x < -xwidth * 0.5 || x > xwidth * 0.5 || y < -yheight * 0.5 || y > yheight * 0.5) {
    RESTORE_XRAY (INDEX_CURRENT_COMP, x, y, z, kx, ky, kz, phi, t, Ex, Ey, Ez, p);
  } else {
    /*get the index of refraction*/
    k = sqrt (kx * kx + ky * ky + kz * kz);
    e = k * K2E;
    /*Material's Number Density of Electrons [e/A^3] incl f' scattering length correction*/
    f = Table_Value (table, e, 1);
    delta = (fixed_delta ? fixed_delta : f / (k * k) * delta_prefactor);
    mu0 = Table_Value (table, e, mu_c) * rho * 1e2;
    beta = mu0 / (2 * k * 1e10);

    /*pick an order with probability proportional to its relative intensity as given by Schnopper*/
    /* n_m(q)/N_0(q)=([sin(Mmpi)/Msin(mpi)]^2 [sin( (a/d)mpi)/mpi]^2 [1+exp(-2qzk)-2exp(-qzk)cos(qzdelta)]*/
    /* M=number of wires in the grating,
     * d grating spacing (period)
     * a width of grating opening (duty-cycle)
     * z the thickness of grating wire
     * k imaginary part of refr index
     * n=1-delta real part of refr index
     * q wavenumber.
     */

    /* path length factor along the incident direction (both angles), used for grooves and substrate */
    sec = k / kz;
    zdepth_eff = zdepth * sec;
    dkx = 2 * M_PI / (period * 1e10); /* grating wave number [AA^-1], the 1e10 factor because period is in m */

    /* Loop over the propagating orders (kx_m = kx + m*dkx, ky is conserved). Pick one with probability
       order_likelihood/tot by weighted reservoir sampling; the ray weight is then multiplied by tot. */
    tot = 0;
    order = 0;
    for (m = -max_order; m <= max_order; m++) {
      if ((kx + m * dkx) * (kx + m * dkx) + ky * ky >= k * k)
        continue; /* evanescent order */
      if (m) {
        order_factor = pow (sin (gamma * m * M_PI) / (m * M_PI), 2.0);
        order_likelihood
            = order_factor * (1 + exp (-2.0 * k * 1e10 * zdepth_eff * beta) - 2.0 * exp (-k * 1e10 * zdepth_eff * beta) * cos (k * 1e10 * zdepth_eff * delta));
      } else {
        order_likelihood = gamma * gamma + (1 - gamma) * (1 - gamma) * exp (-2.0 * k * 1e10 * zdepth_eff * beta)
                           + 2.0 * gamma * (1 - gamma) * exp (-k * 1e10 * zdepth_eff * beta) * cos (k * 1e10 * zdepth_eff * delta);
      }
      tot += order_likelihood;
      if (rand01 () * tot < order_likelihood)
        order = m;
    }
    if (tot <= 0)
      ABSORB;
    p *= tot;

    /* New direction from the grating equation. Each order gets a finite width: the sinc^2 line shape of
       a grating of width xwidth (FWHM 5.57/xwidth in kx) is approximated by a Gaussian. k is conserved. */
    kxn = kx + order * dkx + randnorm () * 2.36 / (xwidth * 1e10);
    kzn = k * k - kxn * kxn - ky * ky;
    if (kzn <= 0)
      ABSORB;
    kzn = sqrt (kzn);

    /* rotate the polarisation with the same rotation that takes the old k to the new k (axis = k x k_new) */
    cx = ky * kzn - kz * ky;
    cy = kz * kxn - kx * kzn;
    cz = kx * ky - ky * kxn;
    if (cx * cx + cy * cy + cz * cz > 0)
      rotate (Ex, Ey, Ez, Ex, Ey, Ez, atan2 (sqrt (cx * cx + cy * cy + cz * cz), kx * kxn + ky * ky + kz * kzn), cx, cy, cz);

    /*change direction*/
    kx = kxn;
    kz = kzn;

    /*do absorption according to mean absorption coefficient in the "slab",
      remembering we can be at an angle: use the path length along the incident direction.
      Only if a substrate table was loaded.*/
    smu0 = 0;
    if (substrate && strlen (substrate))
      smu0 = Table_Value (stable, e, smu_c) * srho * 1e2;

    /*groove absorption is already contained in order_likelihood*/
    p *= exp (-smu0 * sdepth * sec);
    SCATTER;
  }
%}

FINALLY
%{
  Table_Free (&table);
  if (substrate && strlen (substrate))
    Table_Free (&stable);
%}

MCDISPLAY
%{
  int i;
  int n = xwidth / period; /* number of lines, drawing is limited to 100 */
  double w = (1 - gamma) * period; /* width of a bar */
  if (n > 100)
    n = 100;
  if (n < 1)
    n = 1;
  rectangle ("xy", 0, 0, -(sdepth) / 2.0, xwidth, yheight);
  rectangle ("xy", 0, 0, (sdepth) / 2.0, xwidth, yheight);
  for (i = 0; i < n; i++) {
    box (w / 2.0 + (i - n / 2) * period, 0, sdepth / 2.0 + zdepth / 2.0, w, yheight, zdepth, 0, 0, 1, 0);
  }
%}

END

