
===============================  us   ========================================

   us calculates spectral properties of ideal undulator insertion devices.


   US documentation follows.


!+
! Last modification date of this file: Mon Nov 24 21:29:54 CST 2014
! Roger J. Dejus (dejus@aps.anl.gov)
!
! PROGRAM DESCRIPTION:
!  Program to calculate undulator spectra using the Bessel function
!  approximation for an ideal planar undulator or an ideal elliptical
!  undulator (including polarization for both cases).
!  The program may be executed from the XOP interface.
!
! AUTHORS:
!  Roger J. Dejus
!  The Advanced Photon Source
!  Experimental Facilities Division (now in Accelerator Systems Division)
!  Argonne National Laboratory
!
! CREATION DATE:
!  25-MAR-1991
!
! INPUT PARAMETERS:
!  The input parameters are divided into sections related to the storage ring,
!  the undulator, and the quantity to be calculated. Note: when modifying
!  parameters under the Xus interface, double click the input field parameter and
!  press the RETURN key so that the new parameter is accepted.
! Title:				TITLE
! Machine Parameters:
!  Storage ring energy 			ENERGY (GeV)
!  Storage ring current			CUR (mA)
!  RMS relative beam energy spread	SIGE
!  RMS beam size (horizontal)		SIGX (mm)
!  RMS beam size (vertical)		SIGY (mm)
!  RMS beam divergence (horizontal)	SIGX1 (mrad)
!  RMS beam divergence (vertical)	SIGY1 (mrad)
! Undulator Parameters:
!  Period length			PERIOD (cm)
!  Number of periods			NPER
!  Deflection parameter (hor.  field) 	KX (= 0.0 for a regular planar device)
!  Deflection parameter (vert. field) 	KY
! Scan Parameters:
!  Minimum energy			EMINU (eV)
!  Maximum energy EMAX			EMAXU (eV)
!  Number of energy points		NEU
! Pinhole Parameters:
!  Distance from the source		DU (m)
!    (DU=0.0 => angular units)
!  X-coordinate for center of pinhole	XPC (mm) or (mrad)
!  Y-coordinate for center of pinhole	YPC (mm) or (mrad)
!  X-size of pinhole (full width)	XPS (mm) or (mrad)
!  Y-size of pinhole (full width)	YPS (mm) or (mrad)
!    (for angular units (DU=0.0) values are entered in mrad)
!    (X is for the horizontal direction)
!    (Y is for the vertical direction)
!  Number of X subdivisions of pinhole	NXP
!  Number of Y subdivisions of pinhole	NYP
!    (for plotting 3D results with interface Xus, the X-size, Y-size, and the number of
!     of subdivisions in the two directions should be equal)
!
! Mode:
!  Depending on the mode selected, some of the pinhole parameters may be set to different values
!  by the program; see below and check the beginning (header) in the output file.
!  MODE    1    Angular/spatial flux density distribution
!  MODE    2    Angular/spatial flux density spectrum
!  MODE    3    On-axis brilliance spectrum
!  MODE    4    Flux spectrum through a pinhole
!  MODE    5    Flux spectrum integrated over all angles
!  MODE    6    Power density and integrated power
!
!  Angular/spatial flux density distribution
!    - Flux distribution at the chosen minimum energy EMINU.
!      The EMAXU and NEU are not used.
!  Angular/spatial flux density spectrum
!    - Spectrum at a given point in space selected by the XPC and YPC coordinate
!      for the center of the pinhole.
!      The XPS, YPS, NXP and NYP are not used.
!  On-axis brilliance spectrum
!    - The pinhole parameters have no significance here.
!      The DU, XPC, YPC, XPS, YPS, NXP and NYP are not used.
!  Flux spectrum through a pinhole
!    - Spectrum through a pinhole centered at XPC and YPC with total size XPS and YPS.
!  Flux spectrum integrated over all angles.
!    - The pinhole parameters have no significance here.
!      The DU, XPC, YPC, XPS, YPS, NXP and NYP are not used.
!  Power density and integrated power
!    - Integrated over all energies, thus the energy parameters have no
!      significance here. The EMINU, EMAXU and NEU are not used.
!      The SIGE is not used and is set to zero.
!
! Method (N refers to the number of undulator periods):
!  METHOD  1    Non-zero emittance; finite-N
!  METHOD  2    Non-zero emittance; infinite-N
!  METHOD  3    Zero emittance;     finite-N
!  METHOD  4    Non-zero emittance; infinite-N + convolution (Dejus' approach)
!  METHOD 14    Non-zero emittance; infinite-N + convolution (Walker's approach)
!
!  Non-zero emittance; finite-N
!    - Required for MODE 1 "Angular/spatial flux density distribution."
!      Use also for MODE 6 "Power density and integrated power" (any non-zero emittance method may be used).
!      Not allowed for angle-intergrated spectra (MODE 5). Not recommended for other modes due to slow speed.
!  Non-zero emittance; infinite-N
!    - For test purposes; do not use (not available from the XOP menu).
!  Zero emittance; finite-N
!    - Use for zero emittance calculations. Not allowed for angle-integrated spectra (MODE 5).
!  Non-zero emittance; infinite-N/convolution
!    - Recommended for all runs with emittance.
!    - Only METHOD 4 (Dejus' approach) is available on the XOP menu. This method uses an internally
!      generated energy mesh with variable step size: at the location of the harmonics the step size
!      is made small and in between the harmonics the step size is made large.
!
! Harmonic Number:
!  IHARM   0    All harmonics
!  IHARM  -1    Lowest order harmonic (except MODE=6, include to harmonics -IHARM)
!  IHARM   I    I''th harmonic
!
!  All harmonics
!    - Selects all contributing harmonics (generally used).
!  Lowest order harmonic
!    - Selects the lowest order contributing harmonic.
!  Harmonic #
!    - Selects the harmonic number displayed.
!  Edit harmonic number (XOP Menu)
!    - Modifies the displayed harmonic number.
!    - For MODES 1,2,3,4 with METHOD 3 (zero emittance) the IHARM -1 is not used.
!
! Intrinsic Parameters:
!  Several internal parameters used in the calculations. They are commonly not modified
!  by the user. All parameters can be set to zero in which case they default to the values
!  given in the parenthesis.
!
!  NPHI    - Number of steps in angle phi between 0 and pi/2.0 (20).
!            Used in MODES 1,2,3,4,5 for non-zero emittance calculations.
!
!  NALPHA  - Number of steps in angle alpha (gamma*theta) (40).
!            Used in MODES 1,2,3,4 for METHOD 1 (non-zero emittance with finite-N).
!
!  CALPHA2 - Range of angles in alpha^2 in units of the angular equivalent of 1/N (2.0).
!            Used in MODES 1,2,3,4 for METHOD 1 (finite-N) and for METHOD 3 (zero emittance calculations).
!
!  NOMEGA  - Number of steps in photon energy for the natural lineshape (64).
!            Used in MODES 2,3,4,5 for METHOD 14 (infinite-N + convolution Walker's method).
!
!  COMEGA  - Range of photon energies to be included in the natural lineshape in units (energy of fundamental/N) (8.0)
!            The default value covers the range +/- 2/N of the natural lineshape.
!            Used in MODES 2,3,4,5 for METHOD 14 (infinite-N + convolution Walker's method).
!
!  NSIGMA  - Number of standard deviations of the electron beam size and divergence (4).
!            Used in MODES 1,2,3,4,6 for non-zero emittance calculations.
!
! Polarization:
!  The normalized Stokes parameters are calculated including the
!  unpolarized component.
!
!  NOTES:
!
!  1) For MODES 2,3,4,5 the finite-N spectrum is obtained by convoluting the infinite-N
!     spectrum with the natural lineshape. For Walker's method the point spacing in photon
!     energy must be the same for the two curves. This can be achieved as follows: set NEU=0,
!     in which case the spacing is set by the values of NOMEGA and COMEGA and NEU is set accordingly.
!     Set NEU to the approximate number of points desired in the energy range EMINU, EMAXU.
!     A new value of NEU is then calculated which gives the closest match with the spacing
!     of the natural lineshape. In either case EMAXU will also be adjusted so that the convolution
!     can be carried out correctly over the defined energy region.
!
!  2) If DU is set to zero, this indicates that angular flux and power density is to be calculated
!     rather than spatial flux and power density in MODEs 1,2,4 and 6. In this case SIGX and SIGY
!     are ignored, and the acceptance XPC, YPC, XPS, YPS is entered in mrad rather than mm units.
!
!  3) If the acceptance is centred on the axis (XPC=YPC=0.0) then only one quarter of the acceptance
!     needs to be calculated because of symmetry. In this case the range from (0,0) to (XPS/2.0,YPS/2.0)
!     will be divided into NXP,NYP intervals. The printed values of integrated flux and power, including
!     Stokes parameters will however be correct for the total acceptance.
!
!  4) The angle theta (alpha/gamma) is the angle between the undulator axis and the direction of observation.
!     The angle phi is the angle between the projection of the angle of observation in the x-y plane and the x-axis.
!
!  5) For MODE 6 "Power density and integrated power" with non-zero emittance an internally generated
!     cartesian grid is used and none of the intrinsic parameters are used except NSIGMA.
!
!  6) The definition of SIGX must include the contribution of the horizontal dispersion times the beam energy spread.
!     (The dispersion is not an input parameter and hence the user must enter the correct value of SIGX.)
!
!  7) The variable names of some parameters are changed when printed. For example DU is printed as D (distance).
!     EMINU is printed as EMIN, etc. The trailing "U" of a variable name indicates a user value. Some of those
!     are changed inside the code and the actual values used are printed.
!
! DESIGN ISSUES:
!  Program is based on the Bessel function approximation and is valid in the
!  far-field for an ideal sinusoidal magnetic field profile. It is further
!  based on the code URGENT by Richard P. Walker with added features.
!
! COPYRIGHT:
!  This routine may be used at The Advanced Photon Source and any other facility
!  without explicit consent of the author. No warranties are given as to the
!  accuracy of the results.
!
! FILES USED:
!  Input file - us.dat (us.inp for XOP)  File in the user's current directory
!  containing the input parameters.
!  Output file - us.plt (us.out for XOP) File in the user's current directory
!  containing the results of the calculation. The header contains all input parameters
!  and the calculated zero emittance on-axis first harmonic energy (e1), the corresponding
!  wavelength (l1), total power (ptot), and the on-axis power density (pd).
!
! KEYWORDS:
!  Undulator Spectrum, Bessel Function Approximation
!
! LINK/LIBRARY ISSUES:
!  Calls routines BRIGHTE and HUNT. BRIGHTE calculates the brilliance and HUNT
!  searches an array of real numbers (from Numerical Recipes).
!
! PORTABILITY ISSUES:
!  Runs on DEC 3000/400 AXP alpha (Tru64Unix v5.0), SUN (Solaris: SunOS
!  Release v5.6), and Windows 95/98/NT (Pentium and higher).
!
!  Updated October 8, 2013 (Argonne National Laboratory)
!  *** Linux Red Hat Enterprise Linux Workstation release 6.3 (Santiago) ***
!  Red Hat Enterprise Linux (RHEL) 64-bit with the Intel(R) Fortran
!  Intel(R) 64 Compiler XE for applications running on Intel(R) 64,
!  Version 13.1.1.163 Build 2013031, and with GFORTRAN, gcc version 4.4.6 20120305
!  (Red Hat 4.4.6-4) (GCC).
!  *** Sun Solaris SunOS 5.10 Generic_147440-27 sun4u sparc SUNW,Sun-Blade-2500 ***
!  Sun Fortran 90/95 8.4 SunOS_sparc Patch 128231-02 2009/10/20 with the -f77 switch.
!  and with GFORTRAN, gcc version 4.5.1 (GCC).
!  Windows 7/8 64-bit and MacOS X 10.6 (and newer) are also supported.
!  The GFORTRAN compiler (GCC) v4.8.1 was used for compilations on Windows and (GCC) v4.6.1 on MacOS.
!
!  Updated November 24, 2014 (Argonne National Laboratory)
!  *** Linux Red Hat Enterprise Linux Workstation release 6.5 (Santiago) ***
!  Red Hat Enterprise Linux (RHEL) 64-bit with the Intel(R) Fortran
!  Intel(R) 64 Compiler XE for applications running on Intel(R) 64,
!  Version 14.0.1 Build 20131008
!  GNU Fortran (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4)
!  Copyright (C) 2010 Free Software Foundation, Inc.
!
!  *** Sun Solaris SunOS 5.10 Generic_147440-27 sun4u sparc SUNW,Sun-Blade-2500 ***
!  Sun Fortran 90/95 8.4 SunOS_sparc Patch 128231-02 2009/10/20 with the -f77 switch.
!  GNU Fortran (GCC) 4.5.1
!  Copyright (C) 2010 Free Software Foundation, Inc.
!
!  *** Windows 7/8 64-bit ***
!  GNU Fortran (GCC) 4.9.1
!  Copyright (C) 2014 Free Software Foundation, Inc.
!
!  *** MacOS X 10.6 - 10.10 ***
!  GNU Fortran (GCC) 4.9.2 20141029 (prerelease)
!  Copyright (C) 2014 Free Software Foundation, Inc.
!
! TIMING:
!  Execution times vary considerably depending on computer and the
!  quantity being calculated. The zero emittance calculations are fast
!  (few seconds), whereas the non-zero emittance calculations may range from
!  seconds (on-axis brilliance) to an hour (flux spectrum through a pinhole).
!
! EXAMPLES:
! Ex. 1 using the input file ~/test/us.txt (output file becomes us.plt in the current working directory)
! % us ~/test/us.txt
! Ex. 2 using the default input file us.dat in the current working directory (the output file becomes us.plt).
! % us
! Ex. 3 using the input abc in the current working directory (the output file becomes abc.plt).
! % us abc
!
! VERSION:
!  1.94
!
! MODIFICATION HISTORY:
!
!	 Date     | Name  | Description
! ----------------+-------+-----------------------------------------------------
! 06-JUL-1994     | RJD   | Modified value for E1MIN for angle-integrated
!                 |       | spectrum (MODE=5) to be non-zero; gamma*theta
!                 |       | corresponds to sqrt(200) (somewhat arbitrarily
!                 |       | chosen)
! ----------------+-------+-----------------------------------------------------
! 04-OCT-1994     | RJD   | Modified program to include polarization properties.
!                 |       | The four Stokes parameters are now calculated.
!                 |       | Program is for an ideal planar undulator or an ideal
!                 |       | elliptical undulator. Many other changes. The value
!                 |       | of the parameter IHARM has a different meaning.
!                 |       | IHARM=0 now gives 'all harmonics' and IHARM= <0
!                 |       | gives the lowest order harmonic except for the power
!                 |       | option. For the power option, a negative IHARM means
!                 |       | include all harmonics up to and including -IHARM.
!                 |       | This version is 1.6.
! ----------------+-------+-----------------------------------------------------
! 21-JUN-1995     | RJD   | Modified print-out of "Contributing harmonics" in
!		  |       | subroutine PRINT_OUT. Routine incorrectly calculated
!		  |       | IMIN and IMAX for METHOD 4 (Dejus method) for
!		  |       | "Spectral distributions". The spectra and integrated
!		  |       | quantities were calculated correctly and are
!		  |       | unaffected by this modification.
!                 |       | The current version is 1.7.
! ----------------+-------+-----------------------------------------------------
! 04-JAN-1996     | RJD   | Modified the number of decimal places for the sigx1
!                 |       | and sigy1 variables to four in the printout. Added
!                 |       | one more digit for the emax variable to avoid
!                 |       | overflow on rare occasions. Formats 260 and 256 were
!                 |       | changed accordingly.
!                 |       | The current version is 1.8.
! ----------------+-------+-----------------------------------------------------
! 11-NOV-1997     | RJD   | Changed notation: Brightness -> Brilliance.
!                 |       | The current version is 1.9.
! ----------------+-------+-----------------------------------------------------
! 16-JUL-2000     | RJD   | Minor change in the code to compile error-free on
!                 |       | Unix and Windows (no change in results vs. v1.9).
!                 |       | Current version is v1.91.
! ----------------+-------+-----------------------------------------------------
! 02-NOV-2013     | RJD   | Updated date and time routines.
!                 |       | Changed printout of number of decimal places for sigx and sigy.
!                 |       | Increased the number of subdivisions of the pinhole
!                 |       | from 50 to 200 (P_SZ=201).
!                 |       | Changed rank of variable "SL" to become an array in subroutine
!                 |       | ANGLE_INTEGRATION to avoid compilation warning with gfortran.
!                 |       | Current version is v1.92.
! ----------------+-------+-----------------------------------------------------
! 10-JUN-2014     | RJD   | Updated so that an arbitrary input file can be used on the command line.
!                 |       | If no input file is given on the command line then the file 'us.dat'
!                 |       | is assumed ('us.inp' for the XOP version). The output filename is created
!                 |       | from the rootname, which is derived from the input filename using the string after
!                 |       | the last directory separator (/) without its trailing file extension (if it exists).
!                 |       | The output filename is the rootname with the extension (.plt) appended (.out for the
!                 |       | XOP version). Search "standalone" for changing defaults.
!                 |       | Current version is v1.93.
! ----------------+-------+-----------------------------------------------------
! 22-OCT-2014     | RJD   | Added beam energy spread to all modes and introduced parameter SIGE.
!                 |       | Uses routine econ_func() to do the energy convolution.
!                 |       | NOTE: the definition of SIGX remains unchanged and it must include the value of the
!                 |       | horizontal dispersion times the beam energy spread.
!                 |       | Fixed error in SUBROUTINE CONVOLUTE_ENERGY_VSTEP. The array HE() was
!                 |       | accessed with index 0 (out of bounds for J2 = 1). See RJD 10/23/2014.
!                 |       | Fix has no effect on the results because the calculated spectra SP1 would
!                 |       | typically be zero at the boundary.
!                 |       | Completely rewritten to take advantage of modern Fortran 90/95 features including dynamic
!                 |       | allocation of arrays. Array size limitations were removed. Warnings are given if predefined array
!                 !       ! sizes are exceeded but code will run ok although execution times may be quite large.
!                 !       ! Rewrote algorithm for power density distributions (MODE 6) for the non-zero emittance case.
!                 !       ! Now uses a cartesian coordinates for the convolution. Previously used polar coordinates and it gave
!                 !       ! spurios/unreal results for small values of the beam divergence.
!                 |       | Increased values of default parameters NALPHA, NSIGMA, NOMEGA, and COMEGA.
!                 |       | Numerous checks added.
!                 |       | Current version is v1.94.
! ----------------+-------+-----------------------------------------------------
!-