/*******************************************************************************
* Instrument: Template_DCM
*
* %Identification
* Written by: Erik B Knudsen <erkn@fysik.dtu.dk>
* Date: Jan '21
* Origin: DTU Physics
* Version: 1.0
* %INSTRUMENT_SITE: Tests_optics
*
* Template for a vertically defleting DCM
*
* %Description
* Simple skeleton instrument showing a vertically deflecting
* double crystal monochromator. To instead make it horizontally deflecting
* simply add Arms before and after the crystal assembly that rotate by 
* 90 and -90 deg. respectively around the z-axis.
* The crystal is illuminated by a model point source.
*
* %Example: theta=9.17 Detector: emon_dcm1_I=6.14859e-10
*
* %Parameters
* E0:    [keV] Central energy to be emitted by the source. 0=set from theta.
* dE:    [keV] Half width to be emitted by the source
* theta: [deg] Rotation angle of the crystals. 0=set from E0.
* 
* %End
*******************************************************************************/
DEFINE INSTRUMENT Template_DCM(E0=0, dE=0.2,theta=9.17)

DECLARE
%{
  double dcm_gap;
%}

INITIALIZE
%{
   double DM= 5.4909;     // Si d-spacing
   double d = DM/sqrt(3); // <111> reflection |<111>|=3
   dcm_gap  = 0.02;       // gap between the 2 monochromator crystals
   
   if (!theta && E0) {
     // n.lambda = 2 d sin(theta) = 2*PI/E2K / E0 with n=ORDER=1
     double sin_theta = 2*PI/E2K/E0 / 2 / d;
     if (fabs(sin_theta) < 1)
       theta = asin(sin_theta)*RAD2DEG;
   } else if (theta && !E0)
     E0 = 2*PI/E2K / (2*d*sin(theta*DEG2RAD));
   if (!theta || !E0 || dE <=0)
     exit(fprintf(stderr, "%s: ERROR: Monochromator can not reflect E0=%g +/- %g [keV]. Aborting.\n", NAME_INSTRUMENT, E0, dE));
   printf("%s: Monochromator theta=%g [deg] E0=%g [keV]\n", NAME_INSTRUMENT, theta, E0);
%}

TRACE

COMPONENT origin = Progress_bar()
AT (0, 0, 0) RELATIVE ABSOLUTE

COMPONENT source_pt = Source_pt(
    focus_xw=2e-3, 
    focus_yh=1e-3, 
    E0=E0, 
    dE=dE)
AT (0, 0, 0) RELATIVE PREVIOUS

COMPONENT emon_dcm0 = E_monitor(xwidth=0.05, yheight=0.05, filename="emon_dcm0", Emin=E0-dE*2, Emax=E0+dE*2, nE=101)
AT(0,0,1) RELATIVE PREVIOUS

COMPONENT dcm_xtal0 = Bragg_crystal(
    length=0.04, width=0.04, 
    h=1, k=1, l=1, material="Si.txt", V=160.1826)
AT(0,0,0.02) RELATIVE PREVIOUS
ROTATED (-theta,0,0) RELATIVE PREVIOUS

COMPONENT dcm0 = Arm()
AT(0,0,0) RELATIVE dcm_xtal0
ROTATED (-theta,0,0) RELATIVE PREVIOUS

COMPONENT dcm_xtal1 = COPY(dcm_xtal0)
AT(0,dcm_gap, dcm_gap/tan(theta*DEG2RAD)) RELATIVE dcm_xtal0
ROTATED (theta,0,0) RELATIVE dcm0

COMPONENT dcm1 =Arm()
AT(0,0,0) RELATIVE dcm_xtal1
ROTATED (theta,0,0) RELATIVE dcm_xtal1 

COMPONENT emon_dcm1 = COPY(emon_dcm0)(filename="emon_dcm1")
AT(0,0,0.02) RELATIVE dcm1 

END
