/* Automatically generated file. Do not edit. * Format: ANSI C source code * Creator: McStas * Instrument: tof_diffraction.instr (tof_diffraction) * Date: Fri Feb 8 09:52:29 2019 * File: tof_diffraction.c * Compile: cc -o tof_diffraction.out tof_diffraction.c -I/users/troland/McStas/NXS/libnxs_v2 /users/troland/McStas/NXS/libnxs_v2/libnxs.a * CFLAGS= -I/users/troland/McStas/NXS/libnxs_v2 /users/troland/McStas/NXS/libnxs_v2/libnxs.a */ #define MCCODE_STRING "McStas 2.4.1 - Jun. 26, 2017" #define FLAVOR "mcstas" #define FLAVOR_UPPER "MCSTAS" #define MC_USE_DEFAULT_MAIN #define MC_EMBEDDED_RUNTIME #line 1 "mccode-r.h" /******************************************************************************* * * McCode, neutron/xray ray-tracing package * Copyright (C) 1997-2009, All rights reserved * Risoe National Laboratory, Roskilde, Denmark * Institut Laue Langevin, Grenoble, France * * Runtime: share/mccode-r.h * * %Identification * Written by: KN * Date: Aug 29, 1997 * Release: McStas 2.4.1 * Version: $Revision$ * * Runtime system header for McStas/McXtrace. * * In order to use this library as an external library, the following variables * and macros must be declared (see details in the code) * * struct mcinputtable_struct mcinputtable[]; * int mcnumipar; * char mcinstrument_name[], mcinstrument_source[]; * int mctraceenabled, mcdefaultmain; * extern MCNUM mccomp_storein[]; * extern MCNUM mcAbsorbProp[]; * extern MCNUM mcScattered; * #define MCCODE_STRING "the McStas/McXtrace version" * * Usage: Automatically embbeded in the c code. * * $Id$ * *******************************************************************************/ #ifndef MCCODE_R_H #define MCCODE_R_H "$Revision$" #include #include #include #include #include #include #include #include #include #include /* If the runtime is embedded in the simulation program, some definitions can be made static. */ #ifdef MC_EMBEDDED_RUNTIME #define mcstatic static #else #define mcstatic #endif #ifdef __dest_os #if (__dest_os == __mac_os) #define MAC #endif #endif #ifdef __FreeBSD__ #define NEED_STAT_H #endif #if defined(__APPLE__) && defined(__GNUC__) #define NEED_STAT_H #endif #ifdef NEED_STAT_H #include #endif #ifndef MC_PATHSEP_C #ifdef WIN32 #define MC_PATHSEP_C '\\' #define MC_PATHSEP_S "\\" #else /* !WIN32 */ #define MC_PATHSEP_C '/' #define MC_PATHSEP_S "/" #endif /* !WIN32 */ #endif /* MC_PATHSEP_C */ /* the version string is replaced when building distribution with mkdist */ #ifndef MCCODE_STRING #define MCCODE_STRING "McStas 2.4.1 - Jun. 26, 2017" #endif #ifndef MCCODE_DATE #define MCCODE_DATE "Jun. 26, 2017" #endif #ifndef MCCODE_VERSION #define MCCODE_VERSION "2.4.1" #endif #ifndef MCCODE_NAME #define MCCODE_NAME "McStas" #endif #ifndef MCCODE_PARTICLE #define MCCODE_PARTICLE "neutron" #endif #ifndef MCCODE_LIBENV #define MCCODE_LIBENV "MCSTAS" #endif #ifndef FLAVOR_UPPER #define FLAVOR_UPPER MCCODE_NAME #endif #ifdef MC_PORTABLE #ifndef NOSIGNALS #define NOSIGNALS 1 #endif #endif #ifdef MAC #ifndef NOSIGNALS #define NOSIGNALS 1 #endif #endif #if (USE_MPI == 0) #undef USE_MPI #endif #ifdef USE_MPI /* default is to disable signals with MPI, as MPICH uses them to communicate */ #ifndef NOSIGNALS #define NOSIGNALS 1 #endif #endif #if (NOSIGNALS == 0) #undef NOSIGNALS #endif /* Note: the enum instr_formal_types definition MUST be kept synchronized with the one in mccode.h and with the instr_formal_type_names array in cogen.c. */ enum instr_formal_types { instr_type_double, instr_type_int, instr_type_string }; struct mcinputtable_struct { /* defines instrument parameters */ char *name; /* name of parameter */ void *par; /* pointer to instrument parameter (variable) */ enum instr_formal_types type; char *val; /* default value */ }; typedef double MCNUM; typedef struct {MCNUM x, y, z;} Coords; typedef MCNUM Rotation[3][3]; /* the following variables are defined in the McStas generated C code but should be defined externally in case of independent library usage */ #ifndef DANSE extern struct mcinputtable_struct mcinputtable[]; /* list of instrument parameters */ extern int mcnumipar; /* number of instrument parameters */ extern char mcinstrument_name[], mcinstrument_source[]; /* instrument name and filename */ extern char *mcinstrument_exe; /* executable path = argv[0] or NULL */ extern MCNUM mccomp_storein[]; /* 11 coords * number of components in instrument */ extern MCNUM mcAbsorbProp[]; extern MCNUM mcScattered; /* number of SCATTER calls in current component */ extern MCNUM mcRestore; /* Flag to indicate if neutron needs to be restored */ #ifndef MC_ANCIENT_COMPATIBILITY extern int mctraceenabled, mcdefaultmain; #endif #endif /* Useful macros ============================================================ */ /* MPI stuff */ #ifdef USE_MPI #include "mpi.h" #ifdef OMPI_MPI_H /* openmpi does not use signals: we may install our sighandler */ #undef NOSIGNALS #endif /* * MPI_MASTER(i): * execution of i only on master node */ #define MPI_MASTER(statement) { \ if(mpi_node_rank == mpi_node_root)\ { statement; } \ } #ifndef MPI_REDUCE_BLOCKSIZE #define MPI_REDUCE_BLOCKSIZE 1000 #endif int mc_MPI_Sum(double* buf, long count); int mc_MPI_Send(void *sbuf, long count, MPI_Datatype dtype, int dest); int mc_MPI_Recv(void *rbuf, long count, MPI_Datatype dtype, int source); /* MPI_Finalize exits gracefully and should be preferred to MPI_Abort */ #define exit(code) do { \ MPI_Finalize(); \ exit(code); \ } while(0) #else /* !USE_MPI */ #define MPI_MASTER(instr) instr #endif /* USE_MPI */ #ifdef USE_MPI static int mpi_node_count; #endif #ifdef USE_THREADS /* user want threads */ #error Threading (USE_THREADS) support has been removed for very poor efficiency. Use MPI/SSH grid instead. #endif void mcset_ncount(unsigned long long count); /* wrapper to get mcncount */ unsigned long long int mcget_ncount(void); /* wrapper to set mcncount */ unsigned long long mcget_run_num(void); /* wrapper to get mcrun_num=0:mcncount */ /* Following part is only embedded when not redundant with mccode.h ========= */ #ifndef MCCODE_H #ifndef NOSIGNALS #include #define SIG_MESSAGE(msg) strcpy(mcsig_message, msg); #else #define SIG_MESSAGE(msg) #endif /* !NOSIGNALS */ /* Useful macros and constants ============================================== */ #ifndef FLT_MAX #define FLT_MAX 3.40282347E+38F /* max decimal value of a "float" */ #endif #ifndef MIN #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MAX #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif #ifndef SQR #define SQR(x) ( (x) * (x) ) #endif #ifndef SIGN #define SIGN(x) (((x)>0.0)?(1):(-1)) #endif #ifndef PI # ifdef M_PI # define PI M_PI # else # define PI 3.14159265358979323846 # endif #endif #define RAD2MIN ((180*60)/PI) #define MIN2RAD (PI/(180*60)) #define DEG2RAD (PI/180) #define RAD2DEG (180/PI) #define FWHM2RMS 0.424660900144 /* Convert between full-width-half-max and */ #define RMS2FWHM 2.35482004503 /* root-mean-square (standard deviation) */ #define HBAR 1.05457168e-34 /* [Js] h bar Planck constant CODATA 2002 */ #define MNEUTRON 1.67492728e-27 /* [kg] mass of neutron CODATA 2002 */ #define GRAVITY 9.81 /* [m/s^2] gravitational acceleration */ #define NA 6.02214179e23 /* [#atoms/g .mole] Avogadro's number*/ /* wrapper to get absolute and relative position of comp */ /* mccomp_posa and mccomp_posr are defined in McStas generated C code */ #define POS_A_COMP_INDEX(index) \ (mccomp_posa[index]) #define POS_R_COMP_INDEX(index) \ (mccomp_posr[index]) /* number of SCATTER calls in current comp: mcScattered defined in generated C code */ #define SCATTERED mcScattered /* Flag to indicate if neutron needs to be restored: mcRestore defined in generated C code */ #define RESTORE mcRestore /* Retrieve component information from the kernel */ /* Name, position and orientation (both absolute and relative) */ /* Any component: For "redundancy", see comment by KN */ #define tmp_name_comp(comp) #comp #define NAME_COMP(comp) tmp_name_comp(comp) #define tmp_pos_a_comp(comp) (mcposa ## comp) #define POS_A_COMP(comp) tmp_pos_a_comp(comp) #define tmp_pos_r_comp(comp) (mcposr ## comp) #define POS_R_COMP(comp) tmp_pos_r_comp(comp) #define tmp_rot_a_comp(comp) (mcrota ## comp) #define ROT_A_COMP(comp) tmp_rot_a_comp(comp) #define tmp_rot_r_comp(comp) (mcrotr ## comp) #define ROT_R_COMP(comp) tmp_rot_r_comp(comp) /* Current component name, index, position and orientation */ #define NAME_CURRENT_COMP NAME_COMP(mccompcurname) #define INDEX_CURRENT_COMP mccompcurindex #define POS_A_CURRENT_COMP POS_A_COMP(mccompcurname) #define POS_R_CURRENT_COMP POS_R_COMP(mccompcurname) #define ROT_A_CURRENT_COMP ROT_A_COMP(mccompcurname) #define ROT_R_CURRENT_COMP ROT_R_COMP(mccompcurname) /* Note: The two-stage approach to MC_GETPAR is NOT redundant; without it, * after #define C sample, MC_GETPAR(C,x) would refer to component C, not to * component sample. Such are the joys of ANSI C. * Anyway the usage of MCGETPAR requires that we use sometimes bare names... */ #define MC_GETPAR2(comp, par) (mcc ## comp ## _ ## par) #define MC_GETPAR(comp, par) MC_GETPAR2(comp,par) /* MCDISPLAY/trace and debugging message sent to stdout */ #ifdef MC_TRACE_ENABLED #define DEBUG #endif #ifdef DEBUG #define mcDEBUG_INSTR() if(!mcdotrace); else { printf("INSTRUMENT:\n"); printf("Instrument '%s' (%s)\n", mcinstrument_name, mcinstrument_source); } #define mcDEBUG_COMPONENT(name,c,t) if(!mcdotrace); else {\ printf("COMPONENT: \"%s\"\n" \ "POS: %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g\n", \ name, c.x, c.y, c.z, t[0][0], t[0][1], t[0][2], \ t[1][0], t[1][1], t[1][2], t[2][0], t[2][1], t[2][2]); \ mcAccumulatedILength += coords_len(coords_sub(mcLastComp,c)); \ printf("Component %30s AT (%g,%g,%g) %g m from origin\n", name, c.x, c.y, c.z, mcAccumulatedILength); \ mcLastComp=c;\ } #define mcDEBUG_INSTR_END() if(!mcdotrace); else printf("INSTRUMENT END:\n"); #define mcDEBUG_ENTER() if(!mcdotrace); else printf("ENTER:\n"); #define mcDEBUG_COMP(c) if(!mcdotrace); else printf("COMP: \"%s\"\n", c); #define mcDEBUG_LEAVE() if(!mcdotrace); else printf("LEAVE:\n"); #define mcDEBUG_ABSORB() if(!mcdotrace); else printf("ABSORB:\n"); #else #define mcDEBUG_INSTR() #define mcDEBUG_COMPONENT(name,c,t) #define mcDEBUG_INSTR_END() #define mcDEBUG_ENTER() #define mcDEBUG_COMP(c) #define mcDEBUG_LEAVE() #define mcDEBUG_ABSORB() #endif // mcDEBUG_STATE and mcDEBUG_SCATTER are defined by mcstas-r.h and mcxtrace-r.h #ifdef TEST #define test_printf printf #else #define test_printf while(0) printf #endif /* send MCDISPLAY message to stdout to show gemoetry */ void mcdis_magnify(char *what); void mcdis_line(double x1, double y1, double z1, double x2, double y2, double z2); void mcdis_dashed_linemcdis_dashed_line(double x1, double y1, double z1, double x2, double y2, double z2, int n); void mcdis_multiline(int count, ...); void mcdis_rectangle(char* plane, double x, double y, double z, double width, double height); void mcdis_box(double x, double y, double z, double width, double height, double length); void mcdis_circle(char *plane, double x, double y, double z, double r); /* selection of random number generator. default is MT */ #ifndef MC_RAND_ALG #define MC_RAND_ALG 1 #endif #if MC_RAND_ALG == 0 /* Use system random() (not recommended). */ # define MC_RAND_MAX RAND_MAX #elif MC_RAND_ALG == 1 /* "Mersenne Twister", by Makoto Matsumoto and Takuji Nishimura. */ # define MC_RAND_MAX ((unsigned long)0xffffffff) # define random mt_random # define srandom mt_srandom #elif MC_RAND_ALG == 2 /* Algorithm used in McStas CVS-080208 and earlier (not recommended). */ # define MC_RAND_MAX 0x7fffffff # define random mc_random # define srandom mc_srandom #else # error "Bad value for random number generator choice." #endif typedef int mc_int32_t; mc_int32_t mc_random(void); void mc_srandom (unsigned int x); unsigned long mt_random(void); void mt_srandom (unsigned long x); double rand01(); double randpm1(); double rand0max(double max); double randminmax(double min, double max); double randnorm(void); double randtriangle(void); #ifndef DANSE void mcinit(void); void mcraytrace(void); void mcsave(FILE *); void mcfinally(void); void mcdisplay(void); #endif /* simple vector algebra ==================================================== */ #define vec_prod(x, y, z, x1, y1, z1, x2, y2, z2) \ vec_prod_func(&x, &y, &z, x1, y1, z1, x2, y2, z2) mcstatic inline void vec_prod_func(double *x, double *y, double *z, double x1, double y1, double z1, double x2, double y2, double z2); mcstatic inline double scalar_prod( double x1, double y1, double z1, double x2, double y2, double z2); #define NORM(x,y,z) \ norm_func(&x, &y, &z) mcstatic inline void norm_func(double *x, double *y, double *z) { double temp = (*x * *x) + (*y * *y) + (*z * *z); if (temp != 0) { temp = sqrt(temp); *x /= temp; *y /= temp; *z /= temp; } } #define normal_vec(nx, ny, nz, x, y, z) \ normal_vec_func(&(nx), &(ny), &(nz), x, y, z) mcstatic inline void normal_vec_func(double *nx, double *ny, double *nz, double x, double y, double z); /** * Rotate the vector vx,vy,vz psi radians around the vector ax,ay,az * and put the result in x,y,z. */ #define rotate(x, y, z, vx, vy, vz, phi, ax, ay, az) \ do { \ double mcrt_tmpx = (ax), mcrt_tmpy = (ay), mcrt_tmpz = (az); \ double mcrt_vp, mcrt_vpx, mcrt_vpy, mcrt_vpz; \ double mcrt_vnx, mcrt_vny, mcrt_vnz, mcrt_vn1x, mcrt_vn1y, mcrt_vn1z; \ double mcrt_bx, mcrt_by, mcrt_bz; \ double mcrt_cos, mcrt_sin; \ NORM(mcrt_tmpx, mcrt_tmpy, mcrt_tmpz); \ mcrt_vp = scalar_prod((vx), (vy), (vz), mcrt_tmpx, mcrt_tmpy, mcrt_tmpz); \ mcrt_vpx = mcrt_vp*mcrt_tmpx; \ mcrt_vpy = mcrt_vp*mcrt_tmpy; \ mcrt_vpz = mcrt_vp*mcrt_tmpz; \ mcrt_vnx = (vx) - mcrt_vpx; \ mcrt_vny = (vy) - mcrt_vpy; \ mcrt_vnz = (vz) - mcrt_vpz; \ vec_prod(mcrt_bx, mcrt_by, mcrt_bz, \ mcrt_tmpx, mcrt_tmpy, mcrt_tmpz, mcrt_vnx, mcrt_vny, mcrt_vnz); \ mcrt_cos = cos((phi)); mcrt_sin = sin((phi)); \ mcrt_vn1x = mcrt_vnx*mcrt_cos + mcrt_bx*mcrt_sin; \ mcrt_vn1y = mcrt_vny*mcrt_cos + mcrt_by*mcrt_sin; \ mcrt_vn1z = mcrt_vnz*mcrt_cos + mcrt_bz*mcrt_sin; \ (x) = mcrt_vpx + mcrt_vn1x; \ (y) = mcrt_vpy + mcrt_vn1y; \ (z) = mcrt_vpz + mcrt_vn1z; \ } while(0) /** * Mirror (xyz) in the plane given by the point (rx,ry,rz) and normal (nx,ny,nz) * * TODO: This define is seemingly never used... */ #define mirror(x,y,z,rx,ry,rz,nx,ny,nz) \ do { \ double mcrt_tmpx= (nx), mcrt_tmpy = (ny), mcrt_tmpz = (nz); \ double mcrt_tmpt; \ NORM(mcrt_tmpx, mcrt_tmpy, mcrt_tmpz); \ mcrt_tmpt=scalar_prod((rx),(ry),(rz),mcrt_tmpx,mcrt_tmpy,mcrt_tmpz); \ (x) = rx -2 * mcrt_tmpt*mcrt_rmpx; \ (y) = ry -2 * mcrt_tmpt*mcrt_rmpy; \ (z) = rz -2 * mcrt_tmpt*mcrt_rmpz; \ } while (0) Coords coords_set(MCNUM x, MCNUM y, MCNUM z); Coords coords_get(Coords a, MCNUM *x, MCNUM *y, MCNUM *z); Coords coords_add(Coords a, Coords b); Coords coords_sub(Coords a, Coords b); Coords coords_neg(Coords a); Coords coords_scale(Coords b, double scale); double coords_sp(Coords a, Coords b); Coords coords_xp(Coords b, Coords c); double coords_len(Coords a); void coords_print(Coords a); mcstatic inline void coords_norm(Coords* c); void rot_set_rotation(Rotation t, double phx, double phy, double phz); int rot_test_identity(Rotation t); void rot_mul(Rotation t1, Rotation t2, Rotation t3); void rot_copy(Rotation dest, Rotation src); void rot_transpose(Rotation src, Rotation dst); Coords rot_apply(Rotation t, Coords a); void mccoordschange(Coords a, Rotation t, double *x, double *y, double *z, double *vx, double *vy, double *vz, double *sx, double *sy, double *sz); void mccoordschange_polarisation(Rotation t, double *sx, double *sy, double *sz); double mcestimate_error(double N, double p1, double p2); void mcreadparams(void); /* this is now in mcstas-r.h and mcxtrace-r.h as the number of state parameters is no longer equal*/ /* void mcsetstate(double x, double y, double z, double vx, double vy, double vz, double t, double sx, double sy, double sz, double p); */ void mcgenstate(void); /* trajectory/shape intersection routines */ int inside_rectangle(double, double, double, double); int box_intersect(double *dt_in, double *dt_out, double x, double y, double z, double vx, double vy, double vz, double dx, double dy, double dz); int cylinder_intersect(double *t0, double *t1, double x, double y, double z, double vx, double vy, double vz, double r, double h); int sphere_intersect(double *t0, double *t1, double x, double y, double z, double vx, double vy, double vz, double r); /* second order equation roots */ int solve_2nd_order(double *t1, double *t2, double A, double B, double C); /* random vector generation to shape */ void randvec_target_circle(double *xo, double *yo, double *zo, double *solid_angle, double xi, double yi, double zi, double radius); #define randvec_target_sphere randvec_target_circle void randvec_target_rect_angular(double *xo, double *yo, double *zo, double *solid_angle, double xi, double yi, double zi, double height, double width, Rotation A); #define randvec_target_rect(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9) randvec_target_rect_real(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,0,0,0,1) void randvec_target_rect_real(double *xo, double *yo, double *zo, double *solid_angle, double xi, double yi, double zi, double height, double width, Rotation A, double lx, double ly, double lz, int order); /* this is the main() */ int mccode_main(int argc, char *argv[]); #endif /* !MCCODE_H */ #ifndef MCCODE_R_IO_H #define MCCODE_R_IO_H "$Revision$" #if (USE_NEXUS == 0) #undef USE_NEXUS #endif #ifndef CHAR_BUF_LENGTH #define CHAR_BUF_LENGTH 1024 #endif /* I/O section part ========================================================= */ /* ========================================================================== */ /* MCCODE_R_IO_C */ /* ========================================================================== */ /* main DETECTOR structure which stores most information to write to data files */ struct mcdetector_struct { char filename[CHAR_BUF_LENGTH]; /* file name of monitor */ char position[CHAR_BUF_LENGTH]; /* position of detector component */ char component[CHAR_BUF_LENGTH]; /* component instance name */ char instrument[CHAR_BUF_LENGTH]; /* instrument name */ char type[CHAR_BUF_LENGTH]; /* data type, e.g. 0d, 1d, 2d, 3d */ char user[CHAR_BUF_LENGTH]; /* user name, e.g. HOME */ char date[CHAR_BUF_LENGTH]; /* date of simulation end/write time */ char title[CHAR_BUF_LENGTH]; /* title of detector */ char xlabel[CHAR_BUF_LENGTH]; /* X axis label */ char ylabel[CHAR_BUF_LENGTH]; /* Y axis label */ char zlabel[CHAR_BUF_LENGTH]; /* Z axis label */ char xvar[CHAR_BUF_LENGTH]; /* X variable name */ char yvar[CHAR_BUF_LENGTH]; /* Y variable name */ char zvar[CHAR_BUF_LENGTH]; /* Z variable name */ char ncount[CHAR_BUF_LENGTH]; /* number of events initially generated */ char limits[CHAR_BUF_LENGTH]; /* X Y Z limits, e.g. [xmin xmax ymin ymax zmin zmax] */ char variables[CHAR_BUF_LENGTH]; /* variables written into data block */ char statistics[CHAR_BUF_LENGTH]; /* center, mean and half width along axis */ char signal[CHAR_BUF_LENGTH]; /* min max and mean of signal (data block) */ char values[CHAR_BUF_LENGTH]; /* integrated values e.g. [I I_err N] */ double xmin,xmax; /* min max of axes */ double ymin,ymax; double zmin,zmax; double intensity; /* integrated values for data block */ double error; double events; double min; /* statistics for data block */ double max; double mean; double centerX; /* statistics for axes */ double halfwidthX; double centerY; double halfwidthY; int rank; /* dimensionaly of monitor, e.g. 0 1 2 3 */ char istransposed; /* flag to transpose matrix for some formats */ long m,n,p; /* dimensions of data block and along axes */ long date_l; /* same as date, but in sec since 1970 */ double *p0, *p1, *p2; /* pointers to saved data, NULL when freed */ char format[CHAR_BUF_LENGTH]; /* format for file generation */ }; typedef struct mcdetector_struct MCDETECTOR; static char *mcdirname = NULL; /* name of output directory */ static char *mcsiminfo_name = "mccode"; /* default output sim file name */ char *mcformat = NULL; /* NULL (default) or a specific format */ /* file I/O definitions and function prototypes */ #ifndef MC_EMBEDDED_RUNTIME /* the mcstatic variables (from mccode-r.c) */ extern FILE * mcsiminfo_file; /* handle to the output siminfo file */ extern int mcgravitation; /* flag to enable gravitation */ extern int mcdotrace; /* flag to print MCDISPLAY messages */ #else mcstatic FILE *mcsiminfo_file = NULL; #endif /* I/O function prototypes ================================================== */ /* output functions */ MCDETECTOR mcdetector_out_0D(char *t, double p0, double p1, double p2, char *c, Coords pos); MCDETECTOR mcdetector_out_1D(char *t, char *xl, char *yl, char *xvar, double x1, double x2, long n, double *p0, double *p1, double *p2, char *f, char *c, Coords pos); MCDETECTOR mcdetector_out_2D(char *t, char *xl, char *yl, double x1, double x2, double y1, double y2, long m, long n, double *p0, double *p1, double *p2, char *f, char *c, Coords pos); MCDETECTOR mcdetector_out_list(char *t, char *xl, char *yl, long m, long n, double *p1, char *f, char *c, Coords posa); /* wrappers to output functions, that automatically set NAME and POSITION */ #define DETECTOR_OUT(p0,p1,p2) mcdetector_out_0D(NAME_CURRENT_COMP,p0,p1,p2,NAME_CURRENT_COMP,POS_A_CURRENT_COMP) #define DETECTOR_OUT_0D(t,p0,p1,p2) mcdetector_out_0D(t,p0,p1,p2,NAME_CURRENT_COMP,POS_A_CURRENT_COMP) #define DETECTOR_OUT_1D(t,xl,yl,xvar,x1,x2,n,p0,p1,p2,f) \ mcdetector_out_1D(t,xl,yl,xvar,x1,x2,n,p0,p1,p2,f,NAME_CURRENT_COMP,POS_A_CURRENT_COMP) #define DETECTOR_OUT_2D(t,xl,yl,x1,x2,y1,y2,m,n,p0,p1,p2,f) \ mcdetector_out_2D(t,xl,yl,x1,x2,y1,y2,m,n,p0,p1,p2,f,NAME_CURRENT_COMP,POS_A_CURRENT_COMP) #ifdef USE_NEXUS #include "napi.h" NXhandle nxhandle; #endif #endif /* ndef MCCODE_R_IO_H */ #endif /* MCCODE_R_H */ /* End of file "mccode-r.h". */ #line 690 "tof_diffraction.c" #line 1 "mcstas-r.h" /******************************************************************************* * * McStas, neutron ray-tracing package * Copyright (C) 1997-2009, All rights reserved * Risoe National Laboratory, Roskilde, Denmark * Institut Laue Langevin, Grenoble, France * * Runtime: share/mcstas-r.h * * %Identification * Written by: KN * Date: Aug 29, 1997 * Release: McStas X.Y * Version: $Revision$ * * Runtime system header for McStas. * * In order to use this library as an external library, the following variables * and macros must be declared (see details in the code) * * struct mcinputtable_struct mcinputtable[]; * int mcnumipar; * char mcinstrument_name[], mcinstrument_source[]; * int mctraceenabled, mcdefaultmain; * extern MCNUM mccomp_storein[]; * extern MCNUM mcAbsorbProp[]; * extern MCNUM mcScattered; * #define MCCODE_STRING "the McStas version" * * Usage: Automatically embbeded in the c code. * * $Id$ * *******************************************************************************/ #ifndef MCSTAS_R_H #define MCSTAS_R_H "$Revision$" /* Following part is only embedded when not redundent with mcstas.h ========= */ #ifndef MCCODE_H #define AA2MS 629.622368 /* Convert k[1/AA] to v[m/s] */ #define MS2AA 1.58825361e-3 /* Convert v[m/s] to k[1/AA] */ #define K2V AA2MS #define V2K MS2AA #define Q2V AA2MS #define V2Q MS2AA #define SE2V 437.393377 /* Convert sqrt(E)[meV] to v[m/s] */ #define VS2E 5.22703725e-6 /* Convert (v[m/s])**2 to E[meV] */ #define SCATTER do {mcDEBUG_SCATTER(mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, \ mcnlt,mcnlsx,mcnlsy,mcnlsz, mcnlp); mcScattered++;} while(0) #define ABSORB do {mcDEBUG_STATE(mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, \ mcnlt,mcnlsx,mcnlsy,mcnlsz, mcnlp); mcDEBUG_ABSORB(); MAGNET_OFF; goto mcabsorb;} while(0) #define STORE_NEUTRON(index, x, y, z, vx, vy, vz, t, sx, sy, sz, p) \ mcstore_neutron(mccomp_storein,index, x, y, z, vx, vy, vz, t, sx, sy, sz, p); #define RESTORE_NEUTRON(index, x, y, z, vx, vy, vz, t, sx, sy, sz, p) \ mcrestore_neutron(mccomp_storein,index, &x, &y, &z, &vx, &vy, &vz, &t, &sx, &sy, &sz, &p); #define MAGNET_ON \ do { \ mcMagnet = 1; \ } while(0) #define MAGNET_OFF \ do { \ mcMagnet = 0; \ } while(0) #define ALLOW_BACKPROP \ do { \ mcallowbackprop = 1; \ } while(0) #define DISALLOW_BACKPROP \ do { \ mcallowbackprop = 0; \ } while(0) #define PROP_MAGNET(dt) \ do { \ }while (0) /* change coordinates from local system to magnet system */ /* Rotation rotLM, rotTemp; \ Coords posLM = coords_sub(POS_A_CURRENT_COMP, mcMagnetPos); \ rot_transpose(ROT_A_CURRENT_COMP, rotTemp); \ rot_mul(rotTemp, mcMagnetRot, rotLM); \ mcMagnetPrecession(mcnlx, mcnly, mcnlz, mcnlt, mcnlvx, mcnlvy, mcnlvz, \ &mcnlsx, &mcnlsy, &mcnlsz, dt, posLM, rotLM); \ } while(0) */ #define mcPROP_DT(dt) \ do { \ if (mcMagnet && dt > 0) PROP_MAGNET(dt);\ mcnlx += mcnlvx*(dt); \ mcnly += mcnlvy*(dt); \ mcnlz += mcnlvz*(dt); \ mcnlt += (dt); \ if (isnan(p) || isinf(p)) { mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }\ } while(0) /* ADD: E. Farhi, Aug 6th, 2001 PROP_GRAV_DT propagation with acceleration */ #define PROP_GRAV_DT(dt, Ax, Ay, Az) \ do { \ if(dt < 0 && mcallowbackprop == 0) { mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }\ if (mcMagnet) printf("Spin precession gravity\n"); \ mcnlx += mcnlvx*(dt) + (Ax)*(dt)*(dt)/2; \ mcnly += mcnlvy*(dt) + (Ay)*(dt)*(dt)/2; \ mcnlz += mcnlvz*(dt) + (Az)*(dt)*(dt)/2; \ mcnlvx += (Ax)*(dt); \ mcnlvy += (Ay)*(dt); \ mcnlvz += (Az)*(dt); \ mcnlt += (dt); \ DISALLOW_BACKPROP;\ } while(0) #define PROP_DT(dt) \ do { \ if(dt < 0) { RESTORE=1; goto mcabsorbComp; }; \ if (mcgravitation) { Coords mcLocG; double mc_gx, mc_gy, mc_gz; \ mcLocG = rot_apply(ROT_A_CURRENT_COMP, coords_set(0,-GRAVITY,0)); \ coords_get(mcLocG, &mc_gx, &mc_gy, &mc_gz); \ PROP_GRAV_DT(dt, mc_gx, mc_gy, mc_gz); } \ else mcPROP_DT(dt); \ DISALLOW_BACKPROP;\ } while(0) #define PROP_Z0 \ do { \ if (mcgravitation) { Coords mcLocG; int mc_ret; \ double mc_dt, mc_gx, mc_gy, mc_gz; \ mcLocG = rot_apply(ROT_A_CURRENT_COMP, coords_set(0,-GRAVITY,0)); \ coords_get(mcLocG, &mc_gx, &mc_gy, &mc_gz); \ mc_ret = solve_2nd_order(&mc_dt, NULL, -mc_gz/2, -mcnlvz, -mcnlz); \ if (mc_ret && mc_dt>=0) {PROP_GRAV_DT(mc_dt, mc_gx, mc_gy, mc_gz); mcnlz=0;}\ else { if (mcallowbackprop ==0) {mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }}; }\ else mcPROP_Z0; \ DISALLOW_BACKPROP;\ } while(0) #define mcPROP_Z0 \ do { \ double mc_dt; \ if(mcnlvz == 0) { mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }; \ mc_dt = -mcnlz/mcnlvz; \ if(mc_dt < 0 && mcallowbackprop == 0) { mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }; \ mcPROP_DT(mc_dt); \ mcnlz = 0; \ DISALLOW_BACKPROP;\ } while(0) #define PROP_X0 \ do { \ if (mcgravitation) { Coords mcLocG; int mc_ret; \ double mc_dt, mc_gx, mc_gy, mc_gz; \ mcLocG = rot_apply(ROT_A_CURRENT_COMP, coords_set(0,-GRAVITY,0)); \ coords_get(mcLocG, &mc_gx, &mc_gy, &mc_gz); \ mc_ret = solve_2nd_order(&mc_dt, NULL, -mc_gx/2, -mcnlvx, -mcnlx); \ if (mc_ret && mc_dt>=0) PROP_GRAV_DT(mc_dt, mc_gx, mc_gy, mc_gz); \ else { if (mcallowbackprop ==0) {mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }}; }\ else mcPROP_X0; \ DISALLOW_BACKPROP;\ } while(0) #define mcPROP_X0 \ do { \ double mc_dt; \ if(mcnlvx == 0) { mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }; \ mc_dt = -mcnlx/mcnlvx; \ if(mc_dt < 0 && mcallowbackprop == 0) { mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }; \ mcPROP_DT(mc_dt); \ mcnlx = 0; \ DISALLOW_BACKPROP;\ } while(0) #define PROP_Y0 \ do { \ if (mcgravitation) { Coords mcLocG; int mc_ret; \ double mc_dt, mc_gx, mc_gy, mc_gz; \ mcLocG = rot_apply(ROT_A_CURRENT_COMP, coords_set(0,-GRAVITY,0)); \ coords_get(mcLocG, &mc_gx, &mc_gy, &mc_gz); \ mc_ret = solve_2nd_order(&mc_dt, NULL, -mc_gy/2, -mcnlvy, -mcnly); \ if (mc_ret && mc_dt>=0) PROP_GRAV_DT(mc_dt, mc_gx, mc_gy, mc_gz); \ else { if (mcallowbackprop ==0) {mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }}; }\ else mcPROP_Y0; \ DISALLOW_BACKPROP;\ } while(0) #define mcPROP_Y0 \ do { \ double mc_dt; \ if(mcnlvy == 0) { mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }; \ mc_dt = -mcnly/mcnlvy; \ if(mc_dt < 0 && mcallowbackprop == 0) { mcAbsorbProp[INDEX_CURRENT_COMP]++; ABSORB; }; \ mcPROP_DT(mc_dt); \ mcnly = 0; \ DISALLOW_BACKPROP; \ } while(0) /*moved from mccode-r.h*/ void mcsetstate(double x, double y, double z, double vx, double vy, double vz, double t, double sx, double sy, double sz, double p); #ifdef DEBUG #define mcDEBUG_STATE(x,y,z,vx,vy,vz,t,sx,sy,sz,p) if(!mcdotrace); else \ printf("STATE: %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g\n", \ x,y,z,vx,vy,vz,t,sx,sy,sz,p); #define mcDEBUG_SCATTER(x,y,z,vx,vy,vz,t,sx,sy,sz,p) if(!mcdotrace); else \ printf("SCATTER: %g, %g, %g, %g, %g, %g, %g, %g, %g, %g, %g\n", \ x,y,z,vx,vy,vz,t,sx,sy,sz,p); #else #define mcDEBUG_STATE(x,y,z,vx,vy,vz,t,sx,sy,sz,p) #define mcDEBUG_SCATTER(x,y,z,vx,vy,vz,t,sx,sy,sz,p) #endif #endif /* !MCCODE_H */ #endif /* MCSTAS_R_H */ /* End of file "mcstas-r.h". */ #line 923 "tof_diffraction.c" #line 1 "mccode-r.c" /******************************************************************************* * * McCode, neutron/xray ray-tracing package * Copyright (C) 1997-2009, All rights reserved * Risoe National Laboratory, Roskilde, Denmark * Institut Laue Langevin, Grenoble, France * * Runtime: share/mccode-r.c * * %Identification * Written by: KN * Date: Aug 29, 1997 * Release: McStas X.Y/McXtrace X.Y * Version: $Revision$ * * Runtime system for McStas and McXtrace. * Embedded within instrument in runtime mode. * Contains SECTIONS: * MPI handling (sum, send, recv) * format definitions * I/O * mcdisplay support * random numbers * coordinates handling * vectors math (solve 2nd order, normals, randvec...) * parameter handling * signal and main handlers * * Usage: Automatically embbeded in the c code whenever required. * * $Id$ * *******************************************************************************/ /******************************************************************************* * The I/O format definitions and functions *******************************************************************************/ /** Include header files to avoid implicit declarations (not allowed on LLVM) */ #include #include // UNIX specific headers (non-Windows) #if defined(__unix__) || defined(__APPLE__) #include #include #endif #ifndef DANSE #ifdef MC_ANCIENT_COMPATIBILITY int mctraceenabled = 0; int mcdefaultmain = 0; #endif /* else defined directly in the McCode generated C code */ static long mcseed = 0; /* seed for random generator */ static long mcstartdate = 0; /* start simulation time */ static int mcdisable_output_files = 0; /* --no-output-files */ mcstatic int mcgravitation = 0; /* use gravitation flag, for PROP macros */ int mcMagnet = 0; /* magnet stack flag */ mcstatic int mcdotrace = 0; /* flag for --trace and messages for DISPLAY */ int mcallowbackprop = 0; /* flag to enable negative/backprop */ /* Number of particle histories to simulate. */ #ifdef NEUTRONICS mcstatic unsigned long long int mcncount = 1; mcstatic unsigned long long int mcrun_num = 0; #else mcstatic unsigned long long int mcncount = 1000000; mcstatic unsigned long long int mcrun_num = 0; #endif /* NEUTRONICS */ #else #include "mcstas-globals.h" #endif /* !DANSE */ /* SECTION: MPI handling ==================================================== */ #ifdef USE_MPI /* MPI rank */ static int mpi_node_rank; static int mpi_node_root = 0; /******************************************************************************* * mc_MPI_Reduce: Gathers arrays from MPI nodes using Reduce function. *******************************************************************************/ int mc_MPI_Sum(double *sbuf, long count) { if (!sbuf || count <= 0) return(MPI_SUCCESS); /* nothing to reduce */ else { /* we must cut the buffer into blocks not exceeding the MPI max buffer size of 32000 */ long offset=0; double *rbuf=NULL; int length=MPI_REDUCE_BLOCKSIZE; /* defined in mccode-r.h */ int i=0; rbuf = calloc(count, sizeof(double)); if (!rbuf) exit(-fprintf(stderr, "Error: Out of memory %li (mc_MPI_Sum)\n", count*sizeof(double))); while (offset < count) { if (!length || offset+length > count-1) length=count-offset; else length=MPI_REDUCE_BLOCKSIZE; if (MPI_Allreduce((double*)(sbuf+offset), (double*)(rbuf+offset), length, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD) != MPI_SUCCESS) return MPI_ERR_COUNT; offset += length; } for (i=0; i count-1) length=count-offset; else length=MPI_REDUCE_BLOCKSIZE; if (MPI_Send((void*)(sbuf+offset*dsize), length, dtype, dest, tag++, MPI_COMM_WORLD) != MPI_SUCCESS) return MPI_ERR_COUNT; offset += length; } return MPI_SUCCESS; } /* mc_MPI_Send */ /******************************************************************************* * mc_MPI_Recv: Receives arrays from MPI nodes by blocks to avoid buffer limit * the buffer must have been allocated previously. *******************************************************************************/ int mc_MPI_Recv(void *sbuf, long count, MPI_Datatype dtype, int source) { int dsize; long offset=0; int tag=1; int length=MPI_REDUCE_BLOCKSIZE; /* defined in mccode-r.h */ if (!sbuf || count <= 0) return(MPI_SUCCESS); /* nothing to recv */ MPI_Type_size(dtype, &dsize); while (offset < count) { if (offset+length > count-1) length=count-offset; else length=MPI_REDUCE_BLOCKSIZE; if (MPI_Recv((void*)(sbuf+offset*dsize), length, dtype, source, tag++, MPI_COMM_WORLD, MPI_STATUS_IGNORE) != MPI_SUCCESS) return MPI_ERR_COUNT; offset += length; } return MPI_SUCCESS; } /* mc_MPI_Recv */ #endif /* USE_MPI */ /* SECTION: parameters handling ============================================= */ /* Instrument input parameter type handling. */ /******************************************************************************* * mcparm_double: extract double value from 's' into 'vptr' *******************************************************************************/ static int mcparm_double(char *s, void *vptr) { char *p; double *v = (double *)vptr; if (!s) { *v = 0; return(1); } *v = strtod(s, &p); if(*s == '\0' || (p != NULL && *p != '\0') || errno == ERANGE) return 0; /* Failed */ else return 1; /* Success */ } /******************************************************************************* * mcparminfo_double: display parameter type double *******************************************************************************/ static char * mcparminfo_double(char *parmname) { return "double"; } /******************************************************************************* * mcparmerror_double: display error message when failed extract double *******************************************************************************/ static void mcparmerror_double(char *parm, char *val) { fprintf(stderr, "Error: Invalid value '%s' for floating point parameter %s (mcparmerror_double)\n", val, parm); } /******************************************************************************* * mcparmprinter_double: convert double to string *******************************************************************************/ static void mcparmprinter_double(char *f, void *vptr) { double *v = (double *)vptr; sprintf(f, "%g", *v); } /******************************************************************************* * mcparm_int: extract int value from 's' into 'vptr' *******************************************************************************/ static int mcparm_int(char *s, void *vptr) { char *p; int *v = (int *)vptr; long x; if (!s) { *v = 0; return(1); } *v = 0; x = strtol(s, &p, 10); if(x < INT_MIN || x > INT_MAX) return 0; /* Under/overflow */ *v = x; if(*s == '\0' || (p != NULL && *p != '\0') || errno == ERANGE) return 0; /* Failed */ else return 1; /* Success */ } /******************************************************************************* * mcparminfo_int: display parameter type int *******************************************************************************/ static char * mcparminfo_int(char *parmname) { return "int"; } /******************************************************************************* * mcparmerror_int: display error message when failed extract int *******************************************************************************/ static void mcparmerror_int(char *parm, char *val) { fprintf(stderr, "Error: Invalid value '%s' for integer parameter %s (mcparmerror_int)\n", val, parm); } /******************************************************************************* * mcparmprinter_int: convert int to string *******************************************************************************/ static void mcparmprinter_int(char *f, void *vptr) { int *v = (int *)vptr; sprintf(f, "%d", *v); } /******************************************************************************* * mcparm_string: extract char* value from 's' into 'vptr' (copy) *******************************************************************************/ static int mcparm_string(char *s, void *vptr) { char **v = (char **)vptr; if (!s) { *v = NULL; return(1); } *v = (char *)malloc(strlen(s) + 1); if(*v == NULL) { exit(-fprintf(stderr, "Error: Out of memory %li (mcparm_string).\n", (long)strlen(s) + 1)); } strcpy(*v, s); return 1; /* Success */ } /******************************************************************************* * mcparminfo_string: display parameter type string *******************************************************************************/ static char * mcparminfo_string(char *parmname) { return "string"; } /******************************************************************************* * mcparmerror_string: display error message when failed extract string *******************************************************************************/ static void mcparmerror_string(char *parm, char *val) { fprintf(stderr, "Error: Invalid value '%s' for string parameter %s (mcparmerror_string)\n", val, parm); } /******************************************************************************* * mcparmprinter_string: convert string to string (including esc chars) *******************************************************************************/ static void mcparmprinter_string(char *f, void *vptr) { char **v = (char **)vptr; char *p; if (!*v) { *f='\0'; return; } strcpy(f, ""); for(p = *v; *p != '\0'; p++) { switch(*p) { case '\n': strcat(f, "\\n"); break; case '\r': strcat(f, "\\r"); break; case '"': strcat(f, "\\\""); break; case '\\': strcat(f, "\\\\"); break; default: strncat(f, p, 1); } } /* strcat(f, "\""); */ } /* mcparmprinter_string */ /* now we may define the parameter structure, using previous functions */ static struct { int (*getparm)(char *, void *); char * (*parminfo)(char *); void (*error)(char *, char *); void (*printer)(char *, void *); } mcinputtypes[] = { { mcparm_double, mcparminfo_double, mcparmerror_double, mcparmprinter_double }, { mcparm_int, mcparminfo_int, mcparmerror_int, mcparmprinter_int }, { mcparm_string, mcparminfo_string, mcparmerror_string, mcparmprinter_string } }; /******************************************************************************* * mcestimate_error: compute sigma from N,p,p2 in Gaussian large numbers approx *******************************************************************************/ double mcestimate_error(double N, double p1, double p2) { double pmean, n1; if(N <= 1) return p1; pmean = p1 / N; n1 = N - 1; /* Note: underflow may cause p2 to become zero; the fabs() below guards against this. */ return sqrt((N/n1)*fabs(p2 - pmean*pmean)); } double (*mcestimate_error_p) (double V2, double psum, double p2sum)=mcestimate_error; /* ========================================================================== */ /* MCCODE_R_IO_C */ /* ========================================================================== */ #ifndef MCCODE_R_IO_C #define MCCODE_R_IO_C "$Revision$" /* SECTION: file i/o handling ================================================ */ #ifndef HAVE_STRCASESTR // from msysgit: https://code.google.com/p/msysgit/source/browse/compat/strcasestr.c char *strcasestr(const char *haystack, const char *needle) { int nlen = strlen(needle); int hlen = strlen(haystack) - nlen + 1; int i; for (i = 0; i < hlen; i++) { int j; for (j = 0; j < nlen; j++) { unsigned char c1 = haystack[i+j]; unsigned char c2 = needle[j]; if (toupper(c1) != toupper(c2)) goto next; } return (char *) haystack + i; next: ; } return NULL; } #endif #ifndef HAVE_STRCASECMP int strcasecmp( const char *s1, const char *s2 ) { int c1, c2; do { c1 = tolower( (unsigned char) *s1++ ); c2 = tolower( (unsigned char) *s2++ ); } while (c1 == c2 && c1 != 0); return c2 > c1 ? -1 : c1 > c2; } #endif /******************************************************************************* * mcfull_file: allocates a full file name=mcdirname+file. Catenate extension if missing. *******************************************************************************/ char *mcfull_file(char *name, char *ext) { int dirlen=0; char *mem =NULL; dirlen = mcdirname ? strlen(mcdirname) : 0; mem = (char*)malloc(dirlen + strlen(name) + CHAR_BUF_LENGTH); if(!mem) { exit(-fprintf(stderr, "Error: Out of memory %li (mcfull_file)\n", (long)(dirlen + strlen(name) + 256))); } strcpy(mem, ""); /* prepend directory name to path if name does not contain a path */ if (dirlen > 0 && !strchr(name, MC_PATHSEP_C)) { strcat(mem, mcdirname); strcat(mem, MC_PATHSEP_S); } /* dirlen */ strcat(mem, name); if (!strchr(name, '.') && ext && strlen(ext)) { /* add extension if not in file name already */ strcat(mem, "."); strcat(mem, ext); } return(mem); } /* mcfull_file */ /******************************************************************************* * mcnew_file: opens a new file within mcdirname if non NULL * the file is opened in "a" (append, create if does not exist) * the extension 'ext' is added if the file name does not include one. * the last argument is set to 0 if file did not exist, else to 1. *******************************************************************************/ FILE *mcnew_file(char *name, char *ext, int *exists) { char *mem; FILE *file=NULL; if (!name || strlen(name) == 0 || mcdisable_output_files) return(NULL); mem = mcfull_file(name, ext); /* create mcdirname/name.ext */ /* check for existence */ file = fopen(mem, "r"); /* for reading -> fails if does not exist */ if (file) { fclose(file); *exists=1; } else *exists=0; /* open the file for writing/appending */ #ifdef USE_NEXUS if (mcformat && strcasestr(mcformat, "NeXus")) { /* NXhandle nxhandle is defined in the .h with USE_NEXUS */ NXaccess mode = (*exists ? NXACC_CREATE5 | NXACC_RDWR : NXACC_CREATE5); if (NXopen(mem, mode, &nxhandle) != NX_OK) file = NULL; else file = (FILE*)&nxhandle; /* to make it non NULL */ } else #endif file = fopen(mem, "a+"); if(!file) fprintf(stderr, "Warning: could not open output file '%s' for %s (mcnew_file)\n", mem, *exists ? "append" : "create"); free(mem); return file; } /* mcnew_file */ /******************************************************************************* * mcdetector_statistics: compute detector statistics, error bars, [x I I_err N] 1D * RETURN: updated detector structure * Used by: mcdetector_import *******************************************************************************/ MCDETECTOR mcdetector_statistics( MCDETECTOR detector) { if (!detector.p1 || !detector.m || !detector.filename) return(detector); /* compute statistics and update MCDETECTOR structure ===================== */ double sum_z = 0, min_z = 0, max_z = 0; double fmon_x =0, smon_x = 0, fmon_y =0, smon_y=0, mean_z=0; double Nsum=0, P2sum=0; double sum_xz = 0, sum_yz = 0, sum_x = 0, sum_y = 0, sum_x2z = 0, sum_y2z = 0; int i,j; char hasnan=0, hasinf=0; char israw = ((char*)strcasestr(detector.format,"raw") != NULL); double *this_p1=NULL; /* new 1D McCode array [x I E N]. Freed after writing data */ /* if McCode/PGPLOT and rank==1 we create a new m*4 data block=[x I E N] */ if (detector.rank == 1 && strcasestr(detector.format,"McCode")) { this_p1 = (double *)calloc(detector.m*detector.n*detector.p*4, sizeof(double)); if (!this_p1) exit(-fprintf(stderr, "Error: Out of memory creating %li 1D " MCCODE_STRING " data set for file '%s' (mcdetector_import)\n", detector.m*detector.n*detector.p*4*sizeof(double*), detector.filename)); } max_z = min_z = detector.p1[0]; /* compute sum and moments (not for lists) */ if (!strcasestr(detector.format,"list") && detector.m) for(j = 0; j < detector.n*detector.p; j++) { for(i = 0; i < detector.m; i++) { double x,y,z; double N, E; long index= !detector.istransposed ? i*detector.n*detector.p + j : i+j*detector.m; char hasnaninf=0; if (detector.m) x = detector.xmin + (i + 0.5)/detector.m*(detector.xmax - detector.xmin); else x = 0; if (detector.n && detector.p) y = detector.ymin + (j + 0.5)/detector.n/detector.p*(detector.ymax - detector.ymin); else y = 0; z = detector.p1[index]; N = detector.p0 ? detector.p0[index] : 1; E = detector.p2 ? detector.p2[index] : 0; if (detector.p2 && !israw) detector.p2[index] = (*mcestimate_error_p)(detector.p0[index],detector.p1[index],detector.p2[index]); /* set sigma */ if (detector.rank == 1 && this_p1 && strcasestr(detector.format,"McCode")) { /* fill-in 1D McCode array [x I E N] */ this_p1[index*4] = x; this_p1[index*4+1] = z; this_p1[index*4+2] = detector.p2 ? detector.p2[index] : 0; this_p1[index*4+3] = N; } if (isnan(z) || isnan(E) || isnan(N)) hasnaninf=hasnan=1; if (isinf(z) || isinf(E) || isinf(N)) hasnaninf=hasinf=1; /* compute stats integrals */ if (!hasnaninf) { sum_xz += x*z; sum_yz += y*z; sum_x += x; sum_y += y; sum_z += z; sum_x2z += x*x*z; sum_y2z += y*y*z; if (z > max_z) max_z = z; if (z < min_z) min_z = z; Nsum += N; P2sum += E; } } } /* for j */ /* compute 1st and 2nd moments. For lists, sum_z=0 so this is skipped. */ if (sum_z && detector.n*detector.m*detector.p) { fmon_x = sum_xz/sum_z; fmon_y = sum_yz/sum_z; smon_x = sum_x2z/sum_z-fmon_x*fmon_x; smon_x = smon_x > 0 ? sqrt(smon_x) : 0; smon_y = sum_y2z/sum_z-fmon_y*fmon_y; smon_y = smon_y > 0 ? sqrt(smon_y) : 0; mean_z = sum_z/detector.n/detector.m/detector.p; } /* store statistics into detector */ detector.intensity = sum_z; detector.error = Nsum ? (*mcestimate_error_p)(Nsum, sum_z, P2sum) : 0; detector.events = Nsum; detector.min = min_z; detector.max = max_z; detector.mean = mean_z; detector.centerX = fmon_x; detector.halfwidthX= smon_x; detector.centerY = fmon_y; detector.halfwidthY= smon_y; /* if McCode/PGPLOT and rank==1 replace p1 with new m*4 1D McCode and clear others */ if (detector.rank == 1 && this_p1 && strcasestr(detector.format,"McCode")) { detector.p1 = this_p1; detector.n = detector.m; detector.m = 4; detector.p0 = detector.p2 = NULL; detector.istransposed = 1; } if (detector.n*detector.m*detector.p > 1) snprintf(detector.signal, CHAR_BUF_LENGTH, "Min=%g; Max=%g; Mean=%g;", detector.min, detector.max, detector.mean); else strcpy(detector.signal, "None"); snprintf(detector.values, CHAR_BUF_LENGTH, "%g %g %g", detector.intensity, detector.error, detector.events); switch (detector.rank) { case 1: snprintf(detector.statistics, CHAR_BUF_LENGTH, "X0=%g; dX=%g;", detector.centerX, detector.halfwidthX); break; case 2: case 3: snprintf(detector.statistics, CHAR_BUF_LENGTH, "X0=%g; dX=%g; Y0=%g; dY=%g;", detector.centerX, detector.halfwidthX, detector.centerY, detector.halfwidthY); break; default: strcpy(detector.statistics, "None"); } if (hasnan) printf("WARNING: Nan detected in component/file %s %s\n", detector.component, strlen(detector.filename) ? detector.filename : ""); if (hasinf) printf("WARNING: Inf detected in component/file %s %s\n", detector.component, strlen(detector.filename) ? detector.filename : ""); return(detector); } /* mcdetector_statistics */ /******************************************************************************* * mcdetector_import: build detector structure, merge non-lists from MPI * compute basic stat, write "Detector:" line * RETURN: detector structure. Invalid data if detector.p1 == NULL * Invalid detector sets m=0 and filename="" * Simulation data sets m=0 and filename=mcsiminfo_name * This function is equivalent to the old 'mcdetector_out', returning a structure *******************************************************************************/ MCDETECTOR mcdetector_import( char *format, char *component, char *title, long m, long n, long p, char *xlabel, char *ylabel, char *zlabel, char *xvar, char *yvar, char *zvar, double x1, double x2, double y1, double y2, double z1, double z2, char *filename, double *p0, double *p1, double *p2, Coords position) { time_t t; /* for detector.date */ long date_l; /* date as a long number */ char istransposed=0; char c[CHAR_BUF_LENGTH]; /* temp var for signal label */ MCDETECTOR detector; /* build MCDETECTOR structure ============================================= */ /* make sure we do not have NULL for char fields */ /* these also apply to simfile */ strncpy (detector.filename, filename ? filename : "", CHAR_BUF_LENGTH); strncpy (detector.format, format ? format : "McCode" , CHAR_BUF_LENGTH); /* add extension if missing */ if (strlen(detector.filename) && !strchr(detector.filename, '.')) { /* add extension if not in file name already */ strcat(detector.filename, ".dat"); } strncpy (detector.component, component ? component : MCCODE_STRING " component", CHAR_BUF_LENGTH); snprintf(detector.instrument, CHAR_BUF_LENGTH, "%s (%s)", mcinstrument_name, mcinstrument_source); snprintf(detector.user, CHAR_BUF_LENGTH, "%s on %s", getenv("USER") ? getenv("USER") : MCCODE_NAME, getenv("HOST") ? getenv("HOST") : "localhost"); time(&t); /* get current write time */ date_l = (long)t; /* same but as a long */ snprintf(detector.date, CHAR_BUF_LENGTH, "%s", ctime(&t)); if (strlen(detector.date)) detector.date[strlen(detector.date)-1] = '\0'; /* remove last \n in date */ detector.date_l = date_l; if (!mcget_run_num() || mcget_run_num() >= mcget_ncount()) snprintf(detector.ncount, CHAR_BUF_LENGTH, "%llu", mcget_ncount() #ifdef USE_MPI *mpi_node_count #endif ); else snprintf(detector.ncount, CHAR_BUF_LENGTH, "%g/%g", (double)mcget_run_num(), (double)mcget_ncount()); detector.p0 = p0; detector.p1 = p1; detector.p2 = p2; /* handle transposition (not for NeXus) */ if (!strcasestr(detector.format, "NeXus")) { if (m<0 || n<0 || p<0) istransposed = !istransposed; if (strcasestr(detector.format, "transpose")) istransposed = !istransposed; if (istransposed) { /* do the swap once for all */ long i=m; m=n; n=i; } } m=abs(m); n=abs(n); p=abs(p); /* make sure dimensions are positive */ detector.istransposed = istransposed; /* determine detector rank (dimensionality) */ if (!m || !n || !p || !p1) detector.rank = 4; /* invalid: exit with m=0 filename="" */ else if (m*n*p == 1) detector.rank = 0; /* 0D */ else if (n == 1 || m == 1) detector.rank = 1; /* 1D */ else if (p == 1) detector.rank = 2; /* 2D */ else detector.rank = 3; /* 3D */ /* from rank, set type */ switch (detector.rank) { case 0: strcpy(detector.type, "array_0d"); m=n=p=1; break; case 1: snprintf(detector.type, CHAR_BUF_LENGTH, "array_1d(%ld)", m*n*p); m *= n*p; n=p=1; break; case 2: snprintf(detector.type, CHAR_BUF_LENGTH, "array_2d(%ld, %ld)", m, n*p); n *= p; p=1; break; case 3: snprintf(detector.type, CHAR_BUF_LENGTH, "array_3d(%ld, %ld, %ld)", m, n, p); break; default: m=0; strcpy(detector.type, ""); strcpy(detector.filename, "");/* invalid */ } detector.m = m; detector.n = n; detector.p = p; /* these only apply to detector files ===================================== */ snprintf(detector.position, CHAR_BUF_LENGTH, "%g %g %g", position.x, position.y, position.z); /* may also store actual detector orientation in the future */ strncpy(detector.title, title && strlen(title) ? title : component, CHAR_BUF_LENGTH); strncpy(detector.xlabel, xlabel && strlen(xlabel) ? xlabel : "X", CHAR_BUF_LENGTH); /* axis labels */ strncpy(detector.ylabel, ylabel && strlen(ylabel) ? ylabel : "Y", CHAR_BUF_LENGTH); strncpy(detector.zlabel, zlabel && strlen(zlabel) ? zlabel : "Z", CHAR_BUF_LENGTH); strncpy(detector.xvar, xvar && strlen(xvar) ? xvar : "x", CHAR_BUF_LENGTH); /* axis variables */ strncpy(detector.yvar, yvar && strlen(yvar) ? yvar : detector.xvar, CHAR_BUF_LENGTH); strncpy(detector.zvar, zvar && strlen(zvar) ? zvar : detector.yvar, CHAR_BUF_LENGTH); /* set "variables" as e.g. "I I_err N" */ strcpy(c, "I "); if (strlen(detector.zvar)) strncpy(c, detector.zvar,32); else if (strlen(detector.yvar)) strncpy(c, detector.yvar,32); else if (strlen(detector.xvar)) strncpy(c, detector.xvar,32); if (detector.rank == 1) snprintf(detector.variables, CHAR_BUF_LENGTH, "%s %s %s_err N", detector.xvar, c, c); else snprintf(detector.variables, CHAR_BUF_LENGTH, "%s %s_err N", c, c); /* limits */ detector.xmin = x1; detector.xmax = x2; detector.ymin = y1; detector.ymax = y2; detector.zmin = z1; detector.zmax = z2; if (abs(detector.rank) == 1) snprintf(detector.limits, CHAR_BUF_LENGTH, "%g %g", x1, x2); else if (detector.rank == 2) snprintf(detector.limits, CHAR_BUF_LENGTH, "%g %g %g %g", x1, x2, y1, y2); else snprintf(detector.limits, CHAR_BUF_LENGTH, "%g %g %g %g %g %g", x1, x2, y1, y2, z1, z2); /* if MPI and nodes_nb > 1: reduce data sets when using MPI =============== */ #ifdef USE_MPI if (!strcasestr(detector.format,"list") && mpi_node_count > 1 && m) { /* we save additive data: reduce everything into mpi_node_root */ if (p0) mc_MPI_Sum(p0, m*n*p); if (p1) mc_MPI_Sum(p1, m*n*p); if (p2) mc_MPI_Sum(p2, m*n*p); if (!p0) { /* additive signal must be then divided by the number of nodes */ int i; for (i=0; i CHAR_BUF_LENGTH) break; snprintf(ThisParam, CHAR_BUF_LENGTH, " %s(%s)", mcinputtable[i].name, (*mcinputtypes[mcinputtable[i].type].parminfo) (mcinputtable[i].name)); strcat(Parameters, ThisParam); if (strlen(Parameters) >= CHAR_BUF_LENGTH-64) break; } /* output data ============================================================ */ if (f != stdout) fprintf(f, "%sFile: %s%c%s\n", pre, mcdirname, MC_PATHSEP_C, mcsiminfo_name); else fprintf(f, "%sCreator: %s\n", pre, MCCODE_STRING); fprintf(f, "%sSource: %s\n", pre, mcinstrument_source); fprintf(f, "%sParameters: %s\n", pre, Parameters); fprintf(f, "%sTrace_enabled: %s\n", pre, mctraceenabled ? "yes" : "no"); fprintf(f, "%sDefault_main: %s\n", pre, mcdefaultmain ? "yes" : "no"); fprintf(f, "%sEmbedded_runtime: %s\n", pre, #ifdef MC_EMBEDDED_RUNTIME "yes" #else "no" #endif ); fflush(f); } /* mcinfo_out */ /******************************************************************************* * mcruninfo_out: output simulation tags/info (both in SIM and data files) * Used in: mcsiminfo_init (ascii case), mcdetector_out_xD_ascii *******************************************************************************/ static void mcruninfo_out(char *pre, FILE *f) { int i; char Parameters[CHAR_BUF_LENGTH]; if (!f || mcdisable_output_files) return; fprintf(f, "%sFormat: %s%s\n", pre, mcformat && strlen(mcformat) ? mcformat : MCCODE_NAME, mcformat && strcasestr(mcformat,"McCode") ? " with text headers" : ""); fprintf(f, "%sURL: %s\n", pre, "http://www.mccode.org"); fprintf(f, "%sCreator: %s\n", pre, MCCODE_STRING); fprintf(f, "%sInstrument: %s\n", pre, mcinstrument_source); fprintf(f, "%sNcount: %llu\n", pre, mcget_ncount()); fprintf(f, "%sTrace: %s\n", pre, mcdotrace ? "yes" : "no"); fprintf(f, "%sGravitation: %s\n", pre, mcgravitation ? "yes" : "no"); snprintf(Parameters, CHAR_BUF_LENGTH, "%ld", mcseed); fprintf(f, "%sSeed: %s\n", pre, Parameters); fprintf(f, "%sDirectory: %s\n", pre, mcdirname ? mcdirname : "."); #ifdef USE_MPI if (mpi_node_count > 1) fprintf(f, "%sNodes: %i\n", pre, mpi_node_count); #endif /* output parameter string ================================================ */ for(i = 0; i < mcnumipar; i++) { if (mcget_run_num() || (mcinputtable[i].val && strlen(mcinputtable[i].val))) { if (mcinputtable[i].par == NULL) strncpy(Parameters, (mcinputtable[i].val ? mcinputtable[i].val : ""), CHAR_BUF_LENGTH); else (*mcinputtypes[mcinputtable[i].type].printer)(Parameters, mcinputtable[i].par); fprintf(f, "%sParam: %s=%s\n", pre, mcinputtable[i].name, Parameters); } } fflush(f); } /* mcruninfo_out */ /******************************************************************************* * mcsiminfo_out: wrapper to fprintf(mcsiminfo_file) *******************************************************************************/ void mcsiminfo_out(char *format, ...) { va_list ap; if(mcsiminfo_file && !mcdisable_output_files) { va_start(ap, format); vfprintf(mcsiminfo_file, format, ap); va_end(ap); } } /* mcsiminfo_out */ /******************************************************************************* * mcdatainfo_out: output detector header * mcdatainfo_out(prefix, file_handle, detector) writes info to data file *******************************************************************************/ static void mcdatainfo_out(char *pre, FILE *f, MCDETECTOR detector) { if (!f || !detector.m || mcdisable_output_files) return; /* output data ============================================================ */ fprintf(f, "%sDate: %s (%li)\n", pre, detector.date, detector.date_l); fprintf(f, "%stype: %s\n", pre, detector.type); fprintf(f, "%sSource: %s\n", pre, detector.instrument); fprintf(f, "%scomponent: %s\n", pre, detector.component); fprintf(f, "%sposition: %s\n", pre, detector.position); fprintf(f, "%stitle: %s\n", pre, detector.title); fprintf(f, !mcget_run_num() || mcget_run_num() >= mcget_ncount() ? "%sNcount: %s\n" : "%sratio: %s\n", pre, detector.ncount); if (strlen(detector.filename)) { fprintf(f, "%sfilename: %s\n", pre, detector.filename); } fprintf(f, "%sstatistics: %s\n", pre, detector.statistics); fprintf(f, "%ssignal: %s\n", pre, detector.signal); fprintf(f, "%svalues: %s\n", pre, detector.values); if (detector.rank >= 1) { fprintf(f, "%sxvar: %s\n", pre, detector.xvar); fprintf(f, "%syvar: %s\n", pre, detector.yvar); fprintf(f, "%sxlabel: %s\n", pre, detector.xlabel); fprintf(f, "%sylabel: %s\n", pre, detector.ylabel); if (detector.rank > 1) { fprintf(f, "%szvar: %s\n", pre, detector.zvar); fprintf(f, "%szlabel: %s\n", pre, detector.zlabel); } } fprintf(f, abs(detector.rank)==1 ? "%sxlimits: %s\n" : "%sxylimits: %s\n", pre, detector.limits); fprintf(f, "%svariables: %s\n", pre, strcasestr(detector.format, "list") ? detector.ylabel : detector.variables); fflush(f); } /* mcdatainfo_out */ /* mcdetector_out_array_ascii: output a single array to a file * m: columns * n: rows * p: array * f: file handle (already opened) */ static void mcdetector_out_array_ascii(long m, long n, double *p, FILE *f, char istransposed) { if(f) { int i,j; for(j = 0; j < n; j++) { for(i = 0; i < m; i++) { fprintf(f, "%.10g ", p[!istransposed ? i*n + j : j*m+i]); } fprintf(f,"\n"); } } } /* mcdetector_out_array_ascii */ /******************************************************************************* * mcdetector_out_0D_ascii: called by mcdetector_out_0D for ascii output *******************************************************************************/ MCDETECTOR mcdetector_out_0D_ascii(MCDETECTOR detector) { int exists=0; FILE *outfile = NULL; /* Write data set information to simulation description file. */ MPI_MASTER( mcsiminfo_out("\nbegin data\n"); // detector.component mcdatainfo_out(" ", mcsiminfo_file, detector); mcsiminfo_out("end data\n"); /* Don't write if filename is NULL: mcnew_file handles this (return NULL) */ outfile = mcnew_file(detector.component, "dat", &exists); if(outfile) { /* write data file header and entry in simulation description file */ mcruninfo_out( "# ", outfile); mcdatainfo_out("# ", outfile, detector); /* write I I_err N */ fprintf(outfile, "%g %g %g\n", detector.intensity, detector.error, detector.events); fclose(outfile); } ); /* MPI_MASTER */ return(detector); } /* mcdetector_out_0D_ascii */ /******************************************************************************* * mcdetector_out_1D_ascii: called by mcdetector_out_1D for ascii output *******************************************************************************/ MCDETECTOR mcdetector_out_1D_ascii(MCDETECTOR detector) { int exists=0; FILE *outfile = NULL; MPI_MASTER( /* Write data set information to simulation description file. */ mcsiminfo_out("\nbegin data\n"); // detector.filename mcdatainfo_out(" ", mcsiminfo_file, detector); mcsiminfo_out("end data\n"); /* Loop over array elements, writing to file. */ /* Don't write if filename is NULL: mcnew_file handles this (return NULL) */ outfile = mcnew_file(detector.filename, "dat", &exists); if(outfile) { /* write data file header and entry in simulation description file */ mcruninfo_out( "# ", outfile); mcdatainfo_out("# ", outfile, detector); /* output the 1D array columns */ mcdetector_out_array_ascii(detector.m, detector.n, detector.p1, outfile, detector.istransposed); fclose(outfile); } ); /* MPI_MASTER */ return(detector); } /* mcdetector_out_1D_ascii */ /******************************************************************************* * mcdetector_out_2D_ascii: called by mcdetector_out_2D for ascii output *******************************************************************************/ MCDETECTOR mcdetector_out_2D_ascii(MCDETECTOR detector) { int exists=0; FILE *outfile = NULL; MPI_MASTER( /* Loop over array elements, writing to file. */ /* Don't write if filename is NULL: mcnew_file handles this (return NULL) */ outfile = mcnew_file(detector.filename, "dat", &exists); if(outfile) { /* write header only if file has just been created (not appending) */ if (!exists) { /* Write data set information to simulation description file. */ mcsiminfo_out("\nbegin data\n"); // detector.filename mcdatainfo_out(" ", mcsiminfo_file, detector); mcsiminfo_out("end data\n"); mcruninfo_out( "# ", outfile); mcdatainfo_out("# ", outfile, detector); fprintf(outfile, "# Data [%s/%s] %s:\n", detector.component, detector.filename, detector.zvar); } mcdetector_out_array_ascii(detector.m, detector.n*detector.p, detector.p1, outfile, detector.istransposed); if (detector.p2) { fprintf(outfile, "# Errors [%s/%s] %s_err:\n", detector.component, detector.filename, detector.zvar); mcdetector_out_array_ascii(detector.m, detector.n*detector.p, detector.p2, outfile, detector.istransposed); } if (detector.p0) { fprintf(outfile, "# Events [%s/%s] N:\n", detector.component, detector.filename); mcdetector_out_array_ascii(detector.m, detector.n*detector.p, detector.p0, outfile, detector.istransposed); } fclose(outfile); if (!exists) { if (strcasestr(detector.format, "list")) printf("Events: \"%s\"\n", strlen(detector.filename) ? detector.filename : detector.component); } } /* if outfile */ ); /* MPI_MASTER */ #ifdef USE_MPI if (strcasestr(detector.format, "list") && mpi_node_count > 1) { int node_i=0; /* loop along MPI nodes to write sequentially */ for(node_i=0; node_i strlen(original)) n = strlen(original); else original += strlen(original)-n; strncpy(valid, original, n); for (i=0; i < n; i++) { if ( (valid[i] > 122) || (valid[i] < 32) || (strchr("!\"#$%&'()*+,-.:;<=>?@[\\]^`/ \n\r\t", valid[i]) != NULL) ) { if (i) valid[i] = '_'; else valid[i] = 'm'; } } valid[i] = '\0'; return(valid); } /* strcpy_valid */ /* end ascii output section ================================================= */ #ifdef USE_NEXUS /* ========================================================================== */ /* NeXus output */ /* ========================================================================== */ #define nxprintf(...) nxstr('d', __VA_ARGS__) #define nxprintattr(...) nxstr('a', __VA_ARGS__) /******************************************************************************* * nxstr: output a tag=value data set (char) in NeXus/current group * when 'format' is larger that 1024 chars it is used as value for the 'tag' * else the value is assembled with format and following arguments. * type='d' -> data set * 'a' -> attribute for current data set *******************************************************************************/ static int nxstr(char type, NXhandle *f, char *tag, char *format, ...) { va_list ap; char value[CHAR_BUF_LENGTH]; int i; int ret=NX_OK; if (!tag || !format || !strlen(tag) || !strlen(format)) return(NX_OK); /* assemble the value string */ if (strlen(format) < CHAR_BUF_LENGTH) { va_start(ap, format); ret = vsnprintf(value, CHAR_BUF_LENGTH, format, ap); va_end(ap); i = strlen(value); } else { i = strlen(format); } if (type == 'd') { /* open/put/close data set */ if (NXmakedata (f, tag, NX_CHAR, 1, &i) != NX_OK) return(NX_ERROR); NXopendata (f, tag); if (strlen(format) < CHAR_BUF_LENGTH) ret = NXputdata (f, value); else ret = NXputdata (f, format); NXclosedata(f); } else { if (strlen(format) < CHAR_BUF_LENGTH) ret = NXputattr (f, tag, value, strlen(value), NX_CHAR); else ret = NXputattr (f, tag, format, strlen(format), NX_CHAR); } return(ret); } /* nxstr */ /******************************************************************************* * mcinfo_readfile: read a full file into a string buffer which is allocated * Think to free the buffer after use. * Used in: mcinfo_out_nexus (nexus) *******************************************************************************/ char *mcinfo_readfile(char *filename) { FILE *f = fopen(filename, "r"); if (!f) return(NULL); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *string = malloc(fsize + 1); if (string) { int n = fread(string, fsize, 1, f); fclose(f); string[fsize] = 0; } return(string); } /******************************************************************************* * mcinfo_out: output instrument/simulation groups in NeXus file * Used in: mcsiminfo_init (nexus) *******************************************************************************/ static void mcinfo_out_nexus(NXhandle f) { FILE *fid; /* for intrument source code/C/IDF */ char *buffer=NULL; time_t t =time(NULL); /* for date */ char entry0[CHAR_BUF_LENGTH]; int count=0; char name[CHAR_BUF_LENGTH]; char class[CHAR_BUF_LENGTH]; if (!f || mcdisable_output_files) return; /* write NeXus NXroot attributes */ /* automatically added: file_name, HDF5_Version, file_time, NeXus_version */ nxprintattr(f, "creator", "%s generated with " MCCODE_STRING, mcinstrument_name); /* count the number of existing NXentry and create the next one */ NXgetgroupinfo(f, &count, name, class); sprintf(entry0, "entry%i", count+1); /* create the main NXentry (mandatory in NeXus) */ if (NXmakegroup(f, entry0, "NXentry") == NX_OK) if (NXopengroup(f, entry0, "NXentry") == NX_OK) { nxprintf(nxhandle, "program_name", MCCODE_STRING); nxprintf(f, "start_time", ctime(&t)); nxprintf(f, "title", "%s%s%s simulation generated by instrument %s", mcdirname && strlen(mcdirname) ? mcdirname : ".", MC_PATHSEP_S, mcsiminfo_name, mcinstrument_name); nxprintattr(f, "program_name", MCCODE_STRING); nxprintattr(f, "instrument", mcinstrument_name); nxprintattr(f, "simulation", "%s%s%s", mcdirname && strlen(mcdirname) ? mcdirname : ".", MC_PATHSEP_S, mcsiminfo_name); /* write NeXus instrument group */ if (NXmakegroup(f, "instrument", "NXinstrument") == NX_OK) if (NXopengroup(f, "instrument", "NXinstrument") == NX_OK) { int i; char *string=NULL; /* write NeXus parameters(types) data =================================== */ string = (char*)malloc(CHAR_BUF_LENGTH); if (string) { strcpy(string, ""); for(i = 0; i < mcnumipar; i++) { char ThisParam[CHAR_BUF_LENGTH]; snprintf(ThisParam, CHAR_BUF_LENGTH, " %s(%s)", mcinputtable[i].name, (*mcinputtypes[mcinputtable[i].type].parminfo) (mcinputtable[i].name)); if (strlen(string) + strlen(ThisParam) < CHAR_BUF_LENGTH) strcat(string, ThisParam); } nxprintattr(f, "Parameters", string); free(string); } nxprintattr(f, "name", mcinstrument_name); nxprintf (f, "name", mcinstrument_name); nxprintattr(f, "Source", mcinstrument_source); nxprintattr(f, "Trace_enabled", mctraceenabled ? "yes" : "no"); nxprintattr(f, "Default_main", mcdefaultmain ? "yes" : "no"); nxprintattr(f, "Embedded_runtime", #ifdef MC_EMBEDDED_RUNTIME "yes" #else "no" #endif ); /* add instrument source code when available */ buffer = mcinfo_readfile(mcinstrument_source); if (buffer && strlen(buffer)) { long length=strlen(buffer); nxprintf (f, "description", buffer); NXopendata(f,"description"); nxprintattr(f, "file_name", mcinstrument_source); nxprintattr(f, "file_size", "%li", length); nxprintattr(f, "MCCODE_STRING", MCCODE_STRING); NXclosedata(f); nxprintf (f,"instrument_source", "%s " MCCODE_NAME " " MCCODE_PARTICLE " Monte Carlo simulation", mcinstrument_name); free(buffer); } else nxprintf (f, "description", "File %s not found (instrument description %s is missing)", mcinstrument_source, mcinstrument_name); /* add Mantid/IDF.xml when available */ char *IDFfile=NULL; IDFfile = (char*)malloc(CHAR_BUF_LENGTH); sprintf(IDFfile,"%s%s",mcinstrument_source,".xml"); buffer = mcinfo_readfile(IDFfile); if (buffer && strlen(buffer)) { NXmakegroup (nxhandle, "instrument_xml", "NXnote"); NXopengroup (nxhandle, "instrument_xml", "NXnote"); nxprintf(f, "data", buffer); nxprintf(f, "description", "IDF.xml file found with instrument %s", mcinstrument_source); nxprintf(f, "type", "text/xml"); NXclosegroup(f); /* instrument_xml */ free(buffer); } free(IDFfile); NXclosegroup(f); /* instrument */ } /* NXinstrument */ /* write NeXus simulation group */ if (NXmakegroup(f, "simulation", "NXnote") == NX_OK) if (NXopengroup(f, "simulation", "NXnote") == NX_OK) { nxprintattr(f, "name", "%s%s%s", mcdirname && strlen(mcdirname) ? mcdirname : ".", MC_PATHSEP_S, mcsiminfo_name); nxprintf (f, "name", "%s", mcsiminfo_name); nxprintattr(f, "Format", mcformat && strlen(mcformat) ? mcformat : MCCODE_NAME); nxprintattr(f, "URL", "http://www.mccode.org"); nxprintattr(f, "program", MCCODE_STRING); nxprintattr(f, "Instrument",mcinstrument_source); nxprintattr(f, "Trace", mcdotrace ? "yes" : "no"); nxprintattr(f, "Gravitation",mcgravitation ? "yes" : "no"); nxprintattr(f, "Seed", "%li", mcseed); nxprintattr(f, "Directory", mcdirname); #ifdef USE_MPI if (mpi_node_count > 1) nxprintf(f, "Nodes", "%i", mpi_node_count); #endif /* output parameter string ================================================ */ if (NXmakegroup(f, "Param", "NXparameters") == NX_OK) if (NXopengroup(f, "Param", "NXparameters") == NX_OK) { int i; char string[CHAR_BUF_LENGTH]; for(i = 0; i < mcnumipar; i++) { if (mcget_run_num() || (mcinputtable[i].val && strlen(mcinputtable[i].val))) { if (mcinputtable[i].par == NULL) strncpy(string, (mcinputtable[i].val ? mcinputtable[i].val : ""), CHAR_BUF_LENGTH); else (*mcinputtypes[mcinputtable[i].type].printer)(string, mcinputtable[i].par); nxprintf(f, mcinputtable[i].name, "%s", string); nxprintattr(f, mcinputtable[i].name, string); } } NXclosegroup(f); /* Param */ } /* NXparameters */ NXclosegroup(f); /* simulation */ } /* NXsimulation */ /* create a group to hold all monitors */ NXmakegroup(f, "data", "NXdetector"); /* leave the NXentry opened (closed at exit) */ } /* NXentry */ } /* mcinfo_out_nexus */ /******************************************************************************* * mcdatainfo_out_nexus: output detector header * mcdatainfo_out_nexus(detector) create group and write info to NeXus data file * open data:NXdetector then filename:NXdata and write headers/attributes * requires: NXentry to be opened *******************************************************************************/ static void mcdatainfo_out_nexus(NXhandle f, MCDETECTOR detector) { char data_name[32]; if (!f || !detector.m || mcdisable_output_files) return; strcpy_valid(data_name, detector.filename && strlen(detector.filename) ? detector.filename : detector.component); /* the NXdetector group has been created in mcinfo_out_nexus (mcsiminfo_init) */ if (NXopengroup(f, "data", "NXdetector") == NX_OK) { /* create and open the data group */ /* this may fail when appending to list -> ignore/skip */ NXMDisableErrorReporting(); /* unactivate NeXus error messages, as creation may fail */ if (NXmakegroup(f, data_name, "NXdata") == NX_OK) if (NXopengroup(f, data_name, "NXdata") == NX_OK) { /* output metadata (as attributes) ======================================== */ nxprintattr(f, "Date", detector.date); nxprintattr(f, "type", detector.type); nxprintattr(f, "Source", detector.instrument); nxprintattr(f, "component", detector.component); nxprintattr(f, "position", detector.position); nxprintattr(f, "title", detector.title); nxprintattr(f, !mcget_run_num() || mcget_run_num() >= mcget_ncount() ? "Ncount" : "ratio", detector.ncount); if (strlen(detector.filename)) { nxprintattr(f, "filename", detector.filename); } nxprintattr(f, "statistics", detector.statistics); nxprintattr(f, "signal", detector.signal); nxprintattr(f, "values", detector.values); if (detector.rank >= 1) { nxprintattr(f, "xvar", detector.xvar); nxprintattr(f, "yvar", detector.yvar); nxprintattr(f, "xlabel", detector.xlabel); nxprintattr(f, "ylabel", detector.ylabel); if (detector.rank > 1) { nxprintattr(f, "zvar", detector.zvar); nxprintattr(f, "zlabel", detector.zlabel); } } nxprintattr(f, abs(detector.rank)==1 ? "xlimits" : "xylimits", detector.limits); nxprintattr(f, "variables", strcasestr(detector.format, "list") ? detector.ylabel : detector.variables); nxprintf(f, "distance", detector.position); nxprintf(f, "acquisition_mode", strcasestr(detector.format, "list") ? "event" : "summed"); NXclosegroup(f); } /* NXdata (filename) */ NXMEnableErrorReporting(); /* re-enable NeXus error messages */ NXclosegroup(f); } /* NXdetector (data) */ } /* mcdatainfo_out_nexus */ /******************************************************************************* * mcdetector_out_axis_nexus: write detector axis into current NXdata * requires: NXdata to be opened *******************************************************************************/ int mcdetector_out_axis_nexus(NXhandle f, char *label, char *var, int rank, long length, double min, double max) { if (!f || length <= 1 || mcdisable_output_files || max == min) return(NX_OK); else { double axis[length]; char valid[32]; int dim=(int)length; int i; int nprimary=1; /* create an axis from [min:max] */ for(i = 0; i < length; i++) axis[i] = min+(max-min)*(i+0.5)/length; /* create the data set */ strcpy_valid(valid, label); NXcompmakedata(f, valid, NX_FLOAT64, 1, &dim, NX_COMP_LZW, &dim); /* open it */ if (NXopendata(f, valid) != NX_OK) { fprintf(stderr, "Warning: could not open axis rank %i '%s' (NeXus)\n", rank, valid); return(NX_ERROR); } /* put the axis and its attributes */ NXputdata (f, axis); nxprintattr(f, "long_name", label); nxprintattr(f, "short_name", var); NXputattr (f, "axis", &rank, 1, NX_INT32); nxprintattr(f, "units", var); NXputattr (f, "primary", &nprimary, 1, NX_INT32); NXclosedata(f); return(NX_OK); } } /* mcdetector_out_axis_nexus */ /******************************************************************************* * mcdetector_out_array_nexus: write detector array into current NXdata (1D,2D) * requires: NXdata to be opened *******************************************************************************/ int mcdetector_out_array_nexus(NXhandle f, char *part, double *data, MCDETECTOR detector) { int dims[3]={detector.m,detector.n,detector.p}; /* number of elements to write */ int signal=1; int exists=0; int current_dims[3]={0,0,0}; int ret=NX_OK; if (!f || !data || !detector.m || mcdisable_output_files) return(NX_OK); /* when this is a list, we set 1st dimension to NX_UNLIMITED for creation */ if (strcasestr(detector.format, "list")) dims[0] = NX_UNLIMITED; /* create the data set in NXdata group */ NXMDisableErrorReporting(); /* unactivate NeXus error messages, as creation may fail */ /* NXcompmakedata fails with NX_UNLIMITED */ if (strcasestr(detector.format, "list")) ret = NXmakedata( f, part, NX_FLOAT64, detector.rank, dims); else ret = NXcompmakedata(f, part, NX_FLOAT64, detector.rank, dims, NX_COMP_LZW, dims); if (ret != NX_OK) { /* failed: data set already exists */ int datatype=0; int rank=0; exists=1; /* inquire current size of data set (nb of events stored) */ NXopendata(f, part); NXgetinfo(f, &rank, current_dims, &datatype); NXclosedata(f); } NXMEnableErrorReporting(); /* re-enable NeXus error messages */ dims[0] = detector.m; /* restore actual dimension from data writing */ /* open the data set */ if (NXopendata(f, part) == NX_ERROR) { fprintf(stderr, "Warning: could not open DataSet %s '%s' (NeXus)\n", part, detector.title); return(NX_ERROR); } if (strcasestr(detector.format, "list")) { current_dims[1] = current_dims[2] = 0; /* set starting location for writing slab */ NXputslab(f, data, current_dims, dims); if (!exists) printf("Events: \"%s\"\n", strlen(detector.filename) ? detector.filename : detector.component); } else { NXputdata (f, data); } if (strstr(part,"data") || strstr(part, "events")) { NXputattr(f, "signal", &signal, 1, NX_INT32); nxprintattr(f, "short_name", detector.filename && strlen(detector.filename) ? detector.filename : detector.component); } nxprintattr(f, "long_name", "%s '%s'", part, detector.title); NXclosedata(f); return(NX_OK); } /* mcdetector_out_array_nexus */ /******************************************************************************* * mcdetector_out_data_nexus: write detector axes+data into current NXdata * The data:NXdetector is opened, then filename:NXdata * requires: NXentry to be opened *******************************************************************************/ int mcdetector_out_data_nexus(NXhandle f, MCDETECTOR detector) { char data_name[32]; if (!f || !detector.m || mcdisable_output_files) return(NX_OK); strcpy_valid(data_name, detector.filename && strlen(detector.filename) ? detector.filename : detector.component); /* the NXdetector group has been created in mcinfo_out_nexus (mcsiminfo_init) */ if (NXopengroup(f, "data", "NXdetector") == NX_OK) { /* the NXdata group has been created in mcdatainfo_out_nexus */ if (NXopengroup(f, data_name, "NXdata") == NX_OK) { /* write axes, for histogram data sets, not for lists */ if (!strcasestr(detector.format, "list")) { mcdetector_out_axis_nexus(f, detector.xlabel, detector.xvar, 1, detector.m, detector.xmin, detector.xmax); mcdetector_out_axis_nexus(f, detector.ylabel, detector.yvar, 2, detector.n, detector.ymin, detector.ymax); mcdetector_out_axis_nexus(f, detector.zlabel, detector.zvar, 3, detector.p, detector.zmin, detector.zmax); } /* !list */ /* write the actual data (appended if already exists) */ if (!strcasestr(detector.format, "list")) { mcdetector_out_array_nexus(f, "data", detector.p1, detector); mcdetector_out_array_nexus(f, "errors", detector.p2, detector); mcdetector_out_array_nexus(f, "ncount", detector.p0, detector); } else mcdetector_out_array_nexus( f, "events", detector.p1, detector); NXclosegroup(f); } /* NXdata */ NXclosegroup(f); } /* NXdetector */ return(NX_OK); } /* mcdetector_out_array_nexus */ #ifdef USE_MPI /******************************************************************************* * mcdetector_out_list_slaves: slaves send their list data to master which writes * requires: NXentry to be opened * WARNING: this method has a flaw: it requires all nodes to flush the lists * the same number of times. In case one node is just below the buffer size * when finishing (e.g. monitor_nd), it may not trigger save but others may. * Then the number of recv/send is not constant along nodes, and simulation stalls. *******************************************************************************/ MCDETECTOR mcdetector_out_list_slaves(MCDETECTOR detector) { int node_i=0; MPI_MASTER( printf("\n** MPI master gathering slave node list data ** \n"); ); if (mpi_node_rank != mpi_node_root) { /* MPI slave: slaves send their data to master: 2 MPI_Send calls */ /* m, n, p must be sent first, since all slaves do not have the same number of events */ int mnp[3]={detector.m,detector.n,detector.p}; if (mc_MPI_Send(mnp, 3, MPI_INT, mpi_node_root)!= MPI_SUCCESS) fprintf(stderr, "Warning: proc %i to master: MPI_Send mnp list error (mcdetector_out_list_slaves)\n", mpi_node_rank); if (!detector.p1 || mc_MPI_Send(detector.p1, mnp[0]*mnp[1]*mnp[2], MPI_DOUBLE, mpi_node_root) != MPI_SUCCESS) fprintf(stderr, "Warning: proc %i to master: MPI_Send p1 list error: mnp=%i (mcdetector_out_list_slaves)\n", mpi_node_rank, abs(mnp[0]*mnp[1]*mnp[2])); /* slaves are done: sent mnp and p1 */ return (detector); } /* end slaves */ /* MPI master: receive data from slaves sequentially: 2 MPI_Recv calls */ if (mpi_node_rank == mpi_node_root) { for(node_i=0; node_i 1) { mcdetector_out_list_slaves(detector); } #endif /* USE_MPI */ return(detector); } /* mcdetector_out_2D_nexus */ #endif /* USE_NEXUS*/ /* ========================================================================== */ /* Main input functions */ /* DETECTOR_OUT_xD function calls -> ascii or NeXus */ /* ========================================================================== */ /******************************************************************************* * mcsiminfo_init: open SIM and write header *******************************************************************************/ FILE *mcsiminfo_init(FILE *f) { int exists=0; int index; /* check format */ if (!mcformat || !strlen(mcformat) || !strcasecmp(mcformat, "MCSTAS") || !strcasecmp(mcformat, "MCXTRACE") || !strcasecmp(mcformat, "PGPLOT") || !strcasecmp(mcformat, "GNUPLOT") || !strcasecmp(mcformat, "MCCODE") || !strcasecmp(mcformat, "MATLAB")) { mcformat="McCode"; #ifdef USE_NEXUS } else if (strcasestr(mcformat, "NeXus")) { /* Do nothing */ #endif } else { fprintf(stderr, "Warning: You have requested the output format %s which is unsupported by this binary. Resetting to standard %s format.\n",mcformat ,"McCode"); mcformat="McCode"; } /* open the SIM file if not defined yet */ if (mcsiminfo_file || mcdisable_output_files) return (mcsiminfo_file); #ifdef USE_NEXUS /* only master writes NeXus header: calls NXopen(nxhandle) */ if (mcformat && strcasestr(mcformat, "NeXus")) { MPI_MASTER( mcsiminfo_file = mcnew_file(mcsiminfo_name, "h5", &exists); if(!mcsiminfo_file) fprintf(stderr, "Warning: could not open simulation description file '%s'\n", mcsiminfo_name); else mcinfo_out_nexus(nxhandle); ); return(mcsiminfo_file); /* points to nxhandle */ } #endif /* write main description file (only MASTER) */ MPI_MASTER( mcsiminfo_file = mcnew_file(mcsiminfo_name, "sim", &exists); if(!mcsiminfo_file) fprintf(stderr, "Warning: could not open simulation description file '%s'\n", mcsiminfo_name); else { /* write SIM header */ time_t t=time(NULL); mcsiminfo_out("%s simulation description file for %s.\n", MCCODE_NAME, mcinstrument_name); mcsiminfo_out("Date: %s", ctime(&t)); /* includes \n */ mcsiminfo_out("Program: %s\n\n", MCCODE_STRING); mcsiminfo_out("begin instrument: %s\n", mcinstrument_name); mcinfo_out( " ", mcsiminfo_file); mcsiminfo_out("end instrument\n"); mcsiminfo_out("\nbegin simulation: %s\n", mcdirname); mcruninfo_out(" ", mcsiminfo_file); mcsiminfo_out("end simulation\n"); } return (mcsiminfo_file); ); /* MPI_MASTER */ } /* mcsiminfo_init */ /******************************************************************************* * mcsiminfo_close: close SIM *******************************************************************************/ void mcsiminfo_close() { MPI_MASTER( if(mcsiminfo_file && !mcdisable_output_files) { #ifdef USE_NEXUS if (mcformat && strcasestr(mcformat, "NeXus")) { time_t t=time(NULL); nxprintf(nxhandle, "end_time", ctime(&t)); nxprintf(nxhandle, "duration", "%li", (long)t-mcstartdate); NXclosegroup(nxhandle); /* NXentry */ NXclose(&nxhandle); } else #endif fclose(mcsiminfo_file); ); mcsiminfo_file = NULL; } } /* mcsiminfo_close */ /******************************************************************************* * mcdetector_out_0D: wrapper for 0D (single value). * Output single detector/monitor data (p0, p1, p2). * Title is t, component name is c. *******************************************************************************/ MCDETECTOR mcdetector_out_0D(char *t, double p0, double p1, double p2, char *c, Coords posa) { /* import and perform basic detector analysis (and handle MPI reduce) */ MCDETECTOR detector = mcdetector_import(mcformat, c, (t ? t : MCCODE_STRING " data"), 1, 1, 1, "I", "", "", "I", "", "", 0, 0, 0, 0, 0, 0, "", &p0, &p1, &p2, posa); /* write Detector: line */ #ifdef USE_NEXUS if (strcasestr(detector.format, "NeXus")) return(mcdetector_out_0D_nexus(detector)); else #endif return(mcdetector_out_0D_ascii(detector)); } /* mcdetector_out_0D */ /******************************************************************************* * mcdetector_out_1D: wrapper for 1D. * Output 1d detector data (p0, p1, p2) for n bins linearly * distributed across the range x1..x2 (x1 is lower limit of first * bin, x2 is upper limit of last bin). Title is t, axis labels are xl * and yl. File name is f, component name is c. *******************************************************************************/ MCDETECTOR mcdetector_out_1D(char *t, char *xl, char *yl, char *xvar, double x1, double x2, long n, double *p0, double *p1, double *p2, char *f, char *c, Coords posa) { /* import and perform basic detector analysis (and handle MPI_Reduce) */ MCDETECTOR detector = mcdetector_import(mcformat, c, (t ? t : MCCODE_STRING " 1D data"), n, 1, 1, xl, yl, (n > 1 ? "Signal per bin" : " Signal"), xvar, "(I,I_err)", "I", x1, x2, 0, 0, 0, 0, f, p0, p1, p2, posa); /* write Detector: line */ if (!detector.p1 || !detector.m) return(detector); #ifdef USE_NEXUS if (strcasestr(detector.format, "NeXus")) return(mcdetector_out_1D_nexus(detector)); else #endif return(mcdetector_out_1D_ascii(detector)); } /* mcdetector_out_1D */ /******************************************************************************* * mcdetector_out_2D: wrapper for 2D. * special case for list: master creates file first, then slaves append their blocks without header *******************************************************************************/ MCDETECTOR mcdetector_out_2D(char *t, char *xl, char *yl, double x1, double x2, double y1, double y2, long m, long n, double *p0, double *p1, double *p2, char *f, char *c, Coords posa) { char xvar[CHAR_BUF_LENGTH]; char yvar[CHAR_BUF_LENGTH]; /* create short axes labels */ if (xl && strlen(xl)) { strncpy(xvar, xl, CHAR_BUF_LENGTH); xvar[2]='\0'; } else strcpy(xvar, "x"); if (yl && strlen(yl)) { strncpy(yvar, yl, CHAR_BUF_LENGTH); yvar[2]='\0'; } else strcpy(yvar, "y"); MCDETECTOR detector; /* import and perform basic detector analysis (and handle MPI_Reduce) */ if (abs(m) == 1) {/* n>1 on Y, m==1 on X: 1D, no X axis*/ detector = mcdetector_import(mcformat, c, (t ? t : MCCODE_STRING " 1D data"), n, 1, 1, yl, "", "Signal per bin", yvar, "(I,Ierr)", "I", y1, y2, x1, x2, 0, 0, f, p0, p1, p2, posa); /* write Detector: line */ } else if (abs(n)==1) {/* m>1 on X, n==1 on Y: 1D, no Y axis*/ detector = mcdetector_import(mcformat, c, (t ? t : MCCODE_STRING " 1D data"), m, 1, 1, xl, "", "Signal per bin", xvar, "(I,Ierr)", "I", x1, x2, y1, y2, 0, 0, f, p0, p1, p2, posa); /* write Detector: line */ }else { detector = mcdetector_import(mcformat, c, (t ? t : MCCODE_STRING " 2D data"), m, n, 1, xl, yl, "Signal per bin", xvar, yvar, "I", x1, x2, y1, y2, 0, 0, f, p0, p1, p2, posa); /* write Detector: line */ } if (!detector.p1 || !detector.m) return(detector); #ifdef USE_NEXUS if (strcasestr(detector.format, "NeXus")) return(mcdetector_out_2D_nexus(detector)); else #endif return(mcdetector_out_2D_ascii(detector)); } /* mcdetector_out_2D */ /******************************************************************************* * mcdetector_out_list: wrapper for list output (calls out_2D with mcformat+"list"). * m=number of events, n=size of each event *******************************************************************************/ MCDETECTOR mcdetector_out_list(char *t, char *xl, char *yl, long m, long n, double *p1, char *f, char *c, Coords posa) { char format_new[CHAR_BUF_LENGTH]; char *format_org; MCDETECTOR detector; format_org = mcformat; strcpy(format_new, mcformat); strcat(format_new, " list"); mcformat = format_new; detector = mcdetector_out_2D(t, xl, yl, 1,abs(m),1,abs(n), m,n, NULL, p1, NULL, f, c, posa); mcformat = format_org; return(detector); } /******************************************************************************* * mcuse_dir: set data/sim storage directory and create it, * or exit with error if exists ******************************************************************************/ static void mcuse_dir(char *dir) { if (!dir || !strlen(dir)) return; #ifdef MC_PORTABLE fprintf(stderr, "Error: " "Directory output cannot be used with portable simulation (mcuse_dir)\n"); exit(1); #else /* !MC_PORTABLE */ /* handle file://directory URL type */ if (strncmp(dir, "file://", strlen("file://"))) mcdirname = dir; else mcdirname = dir+strlen("file://"); MPI_MASTER( if(mkdir(mcdirname, 0777)) { #ifndef DANSE fprintf(stderr, "Error: unable to create directory '%s' (mcuse_dir)\n", dir); fprintf(stderr, "(Maybe the directory already exists?)\n"); #endif #ifdef USE_MPI MPI_Abort(MPI_COMM_WORLD, -1); #endif exit(-1); } ); /* MPI_MASTER */ /* remove trailing PATHSEP (if any) */ while (strlen(mcdirname) && mcdirname[strlen(mcdirname) - 1] == MC_PATHSEP_C) mcdirname[strlen(mcdirname) - 1]='\0'; #endif /* !MC_PORTABLE */ } /* mcuse_dir */ /******************************************************************************* * mcinfo: display instrument simulation info to stdout and exit *******************************************************************************/ static void mcinfo(void) { fprintf(stdout, "begin instrument: %s\n", mcinstrument_name); mcinfo_out(" ", stdout); fprintf(stdout, "end instrument\n"); fprintf(stdout, "begin simulation: %s\n", mcdirname ? mcdirname : "."); mcruninfo_out(" ", stdout); fprintf(stdout, "end simulation\n"); exit(0); /* includes MPI_Finalize in MPI mode */ } /* mcinfo */ #endif /* ndef MCCODE_R_IO_C */ /* end of the I/O section =================================================== */ /******************************************************************************* * mcset_ncount: set total number of rays to generate *******************************************************************************/ void mcset_ncount(unsigned long long int count) { mcncount = count; } /* mcget_ncount: get total number of rays to generate */ unsigned long long int mcget_ncount(void) { return mcncount; } /* mcget_run_num: get curent number of rays in TRACE */ unsigned long long int mcget_run_num(void) { return mcrun_num; } /* mcsetn_arg: get ncount from a string argument */ static void mcsetn_arg(char *arg) { mcset_ncount((long long int) strtod(arg, NULL)); } /* mcsetseed: set the random generator seed from a string argument */ static void mcsetseed(char *arg) { mcseed = atol(arg); if(mcseed) { srandom(mcseed); } else { fprintf(stderr, "Error: seed must not be zero (mcsetseed)\n"); exit(1); } } /* Following part is only embedded when not redundent with mccode-r.h ========= */ #ifndef MCCODE_H /* SECTION: MCDISPLAY support. =============================================== */ /******************************************************************************* * Just output MCDISPLAY keywords to be caught by an external plotter client. *******************************************************************************/ void mcdis_magnify(char *what){ printf("MCDISPLAY: magnify('%s')\n", what); } void mcdis_line(double x1, double y1, double z1, double x2, double y2, double z2){ printf("MCDISPLAY: multiline(2,%g,%g,%g,%g,%g,%g)\n", x1,y1,z1,x2,y2,z2); } void mcdis_dashed_line(double x1, double y1, double z1, double x2, double y2, double z2, int n){ int i; const double dx = (x2-x1)/(2*n+1); const double dy = (y2-y1)/(2*n+1); const double dz = (z2-z1)/(2*n+1); for(i = 0; i < n+1; i++) mcdis_line(x1 + 2*i*dx, y1 + 2*i*dy, z1 + 2*i*dz, x1 + (2*i+1)*dx, y1 + (2*i+1)*dy, z1 + (2*i+1)*dz); } void mcdis_multiline(int count, ...){ va_list ap; double x,y,z; printf("MCDISPLAY: multiline(%d", count); va_start(ap, count); while(count--) { x = va_arg(ap, double); y = va_arg(ap, double); z = va_arg(ap, double); printf(",%g,%g,%g", x, y, z); } va_end(ap); printf(")\n"); } void mcdis_rectangle(char* plane, double x, double y, double z, double width, double height){ /* draws a rectangle in the plane */ /* x is ALWAYS width and y is ALWAYS height */ if (strcmp("xy", plane)==0) { mcdis_multiline(5, x - width/2, y - height/2, z, x + width/2, y - height/2, z, x + width/2, y + height/2, z, x - width/2, y + height/2, z, x - width/2, y - height/2, z); } else if (strcmp("xz", plane)==0) { mcdis_multiline(5, x - width/2, y, z - height/2, x + width/2, y, z - height/2, x + width/2, y, z + height/2, x - width/2, y, z + height/2, x - width/2, y, z - height/2); } else if (strcmp("yz", plane)==0) { mcdis_multiline(5, x, y - height/2, z - width/2, x, y - height/2, z + width/2, x, y + height/2, z + width/2, x, y + height/2, z - width/2, x, y - height/2, z - width/2); } else { fprintf(stderr, "Error: Definition of plane %s unknown\n", plane); exit(1); } } /* draws a box with center at (x, y, z) and width (deltax), height (deltay), length (deltaz) */ void mcdis_box(double x, double y, double z, double width, double height, double length){ mcdis_rectangle("xy", x, y, z-length/2, width, height); mcdis_rectangle("xy", x, y, z+length/2, width, height); mcdis_line(x-width/2, y-height/2, z-length/2, x-width/2, y-height/2, z+length/2); mcdis_line(x-width/2, y+height/2, z-length/2, x-width/2, y+height/2, z+length/2); mcdis_line(x+width/2, y-height/2, z-length/2, x+width/2, y-height/2, z+length/2); mcdis_line(x+width/2, y+height/2, z-length/2, x+width/2, y+height/2, z+length/2); } void mcdis_circle(char *plane, double x, double y, double z, double r){ printf("MCDISPLAY: circle('%s',%g,%g,%g,%g)\n", plane, x, y, z, r); } /* SECTION: coordinates handling ============================================ */ /******************************************************************************* * Since we use a lot of geometric calculations using Cartesian coordinates, * we collect some useful routines here. However, it is also permissible to * work directly on the underlying struct coords whenever that is most * convenient (that is, the type Coords is not abstract). * * Coordinates are also used to store rotation angles around x/y/z axis. * * Since coordinates are used much like a basic type (such as double), the * structure itself is passed and returned, rather than a pointer. * * At compile-time, the values of the coordinates may be unknown (for example * a motor position). Hence coordinates are general expressions and not simple * numbers. For this we used the type Coords_exp which has three CExp * fields. For runtime (or calculations possible at compile time), we use * Coords which contains three double fields. *******************************************************************************/ /* coords_set: Assign coordinates. */ Coords coords_set(MCNUM x, MCNUM y, MCNUM z) { Coords a; a.x = x; a.y = y; a.z = z; return a; } /* coords_get: get coordinates. Required when 'x','y','z' are #defined as ray pars */ Coords coords_get(Coords a, MCNUM *x, MCNUM *y, MCNUM *z) { *x = a.x; *y = a.y; *z = a.z; return a; } /* coords_add: Add two coordinates. */ Coords coords_add(Coords a, Coords b) { Coords c; c.x = a.x + b.x; c.y = a.y + b.y; c.z = a.z + b.z; if (fabs(c.z) < 1e-14) c.z=0.0; return c; } /* coords_sub: Subtract two coordinates. */ Coords coords_sub(Coords a, Coords b) { Coords c; c.x = a.x - b.x; c.y = a.y - b.y; c.z = a.z - b.z; if (fabs(c.z) < 1e-14) c.z=0.0; return c; } /* coords_neg: Negate coordinates. */ Coords coords_neg(Coords a) { Coords b; b.x = -a.x; b.y = -a.y; b.z = -a.z; return b; } /* coords_scale: Scale a vector. */ Coords coords_scale(Coords b, double scale) { Coords a; a.x = b.x*scale; a.y = b.y*scale; a.z = b.z*scale; return a; } /* coords_sp: Scalar product: a . b */ double coords_sp(Coords a, Coords b) { double value; value = a.x*b.x + a.y*b.y + a.z*b.z; return value; } /* coords_xp: Cross product: a = b x c. */ Coords coords_xp(Coords b, Coords c) { Coords a; a.x = b.y*c.z - c.y*b.z; a.y = b.z*c.x - c.z*b.x; a.z = b.x*c.y - c.x*b.y; return a; } /* coords_len: Gives length of coords set. */ double coords_len(Coords a) { return sqrt(a.x*a.x + a.y*a.y + a.z*a.z); } /* coords_mirror: Mirror a in plane (through the origin) defined by normal n*/ Coords coords_mirror(Coords a, Coords n) { double t = scalar_prod(n.x, n.y, n.z, n.x, n.y, n.z); Coords b; if (t!=1) { t = sqrt(t); n.x /= t; n.y /= t; n.z /= t; } t=scalar_prod(a.x, a.y, a.z, n.x, n.y, n.z); b.x = a.x-2*t*n.x; b.y = a.y-2*t*n.y; b.z = a.z-2*t*n.z; return b; } /* coords_print: Print out vector values. */ void coords_print(Coords a) { fprintf(stdout, "(%f, %f, %f)\n", a.x, a.y, a.z); return; } mcstatic inline void coords_norm(Coords* c) { double temp = coords_sp(*c,*c); // Skip if we will end dividing by zero if (temp == 0) return; temp = sqrt(temp); c->x /= temp; c->y /= temp; c->z /= temp; } /******************************************************************************* * The Rotation type implements a rotation transformation of a coordinate * system in the form of a double[3][3] matrix. * * Contrary to the Coords type in coords.c, rotations are passed by * reference. Functions that yield new rotations do so by writing to an * explicit result parameter; rotations are not returned from functions. The * reason for this is that arrays cannot by returned from functions (though * structures can; thus an alternative would have been to wrap the * double[3][3] array up in a struct). Such are the ways of C programming. * * A rotation represents the tranformation of the coordinates of a vector when * changing between coordinate systems that are rotated with respect to each * other. For example, suppose that coordinate system Q is rotated 45 degrees * around the Z axis with respect to coordinate system P. Let T be the * rotation transformation representing a 45 degree rotation around Z. Then to * get the coordinates of a vector r in system Q, apply T to the coordinates * of r in P. If r=(1,0,0) in P, it will be (sqrt(1/2),-sqrt(1/2),0) in * Q. Thus we should be careful when interpreting the sign of rotation angles: * they represent the rotation of the coordinate systems, not of the * coordinates (which has opposite sign). *******************************************************************************/ /******************************************************************************* * rot_set_rotation: Get transformation for rotation first phx around x axis, * then phy around y, then phz around z. *******************************************************************************/ void rot_set_rotation(Rotation t, double phx, double phy, double phz) { if ((phx == 0) && (phy == 0) && (phz == 0)) { t[0][0] = 1.0; t[0][1] = 0.0; t[0][2] = 0.0; t[1][0] = 0.0; t[1][1] = 1.0; t[1][2] = 0.0; t[2][0] = 0.0; t[2][1] = 0.0; t[2][2] = 1.0; } else { double cx = cos(phx); double sx = sin(phx); double cy = cos(phy); double sy = sin(phy); double cz = cos(phz); double sz = sin(phz); t[0][0] = cy*cz; t[0][1] = sx*sy*cz + cx*sz; t[0][2] = sx*sz - cx*sy*cz; t[1][0] = -cy*sz; t[1][1] = cx*cz - sx*sy*sz; t[1][2] = sx*cz + cx*sy*sz; t[2][0] = sy; t[2][1] = -sx*cy; t[2][2] = cx*cy; } } /******************************************************************************* * rot_test_identity: Test if rotation is identity *******************************************************************************/ int rot_test_identity(Rotation t) { return (t[0][0] + t[1][1] + t[2][2] == 3); } /******************************************************************************* * rot_mul: Matrix multiplication of transformations (this corresponds to * combining transformations). After rot_mul(T1, T2, T3), doing T3 is * equal to doing first T2, then T1. * Note that T3 must not alias (use the same array as) T1 or T2. *******************************************************************************/ void rot_mul(Rotation t1, Rotation t2, Rotation t3) { if (rot_test_identity(t1)) { rot_copy(t3, t2); } else if (rot_test_identity(t2)) { rot_copy(t3, t1); } else { int i,j; for(i = 0; i < 3; i++) for(j = 0; j < 3; j++) t3[i][j] = t1[i][0]*t2[0][j] + t1[i][1]*t2[1][j] + t1[i][2]*t2[2][j]; } } /******************************************************************************* * rot_copy: Copy a rotation transformation (arrays cannot be assigned in C). *******************************************************************************/ void rot_copy(Rotation dest, Rotation src) { int i,j; for(i = 0; i < 3; i++) for(j = 0; j < 3; j++) dest[i][j] = src[i][j]; } /******************************************************************************* * rot_transpose: Matrix transposition, which is inversion for Rotation matrices *******************************************************************************/ void rot_transpose(Rotation src, Rotation dst) { dst[0][0] = src[0][0]; dst[0][1] = src[1][0]; dst[0][2] = src[2][0]; dst[1][0] = src[0][1]; dst[1][1] = src[1][1]; dst[1][2] = src[2][1]; dst[2][0] = src[0][2]; dst[2][1] = src[1][2]; dst[2][2] = src[2][2]; } /******************************************************************************* * rot_apply: returns t*a *******************************************************************************/ Coords rot_apply(Rotation t, Coords a) { Coords b; if (rot_test_identity(t)) { return a; } else { b.x = t[0][0]*a.x + t[0][1]*a.y + t[0][2]*a.z; b.y = t[1][0]*a.x + t[1][1]*a.y + t[1][2]*a.z; b.z = t[2][0]*a.x + t[2][1]*a.y + t[2][2]*a.z; return b; } } /** * Pretty-printing of rotation matrices. */ void rot_print(Rotation rot) { printf("[ %4.2f %4.2f %4.2f ]\n", rot[0][0], rot[0][1], rot[0][2]); printf("[ %4.2f %4.2f %4.2f ]\n", rot[1][0], rot[1][1], rot[1][2]); printf("[ %4.2f %4.2f %4.2f ]\n\n", rot[2][0], rot[2][1], rot[2][2]); } /** * Vector product: used by vec_prod (mccode-r.h). Use coords_xp for Coords. */ mcstatic inline void vec_prod_func(double *x, double *y, double *z, double x1, double y1, double z1, double x2, double y2, double z2) { *x = (y1)*(z2) - (y2)*(z1); *y = (z1)*(x2) - (z2)*(x1); *z = (x1)*(y2) - (x2)*(y1); } /** * Scalar product: use coords_sp for Coords. */ mcstatic inline double scalar_prod( double x1, double y1, double z1, double x2, double y2, double z2) { return ((x1 * x2) + (y1 * y2) + (z1 * z2)); } /******************************************************************************* * mccoordschange: applies rotation to (x y z) and (vx vy vz) and Spin (sx,sy,sz) *******************************************************************************/ void mccoordschange(Coords a, Rotation t, double *x, double *y, double *z, double *vx, double *vy, double *vz, double *sx, double *sy, double *sz) { Coords b, c; b.x = *x; b.y = *y; b.z = *z; c = rot_apply(t, b); b = coords_add(c, a); *x = b.x; *y = b.y; *z = b.z; if ( (vz && vy && vx) && (*vz != 0.0 || *vx != 0.0 || *vy != 0.0) ) mccoordschange_polarisation(t, vx, vy, vz); if ( (sz && sy && sx) && (*sz != 0.0 || *sx != 0.0 || *sy != 0.0) ) mccoordschange_polarisation(t, sx, sy, sz); } /******************************************************************************* * mccoordschange_polarisation: applies rotation to vector (sx sy sz) *******************************************************************************/ void mccoordschange_polarisation(Rotation t, double *sx, double *sy, double *sz) { Coords b, c; b.x = *sx; b.y = *sy; b.z = *sz; c = rot_apply(t, b); *sx = c.x; *sy = c.y; *sz = c.z; } /* SECTION: vector math ==================================================== */ /* normal_vec_func: Compute normal vector to (x,y,z). */ mcstatic inline void normal_vec_func(double *nx, double *ny, double *nz, double x, double y, double z) { double ax = fabs(x); double ay = fabs(y); double az = fabs(z); double l; if(x == 0 && y == 0 && z == 0) { *nx = 0; *ny = 0; *nz = 0; return; } if(ax < ay) { if(ax < az) { /* Use X axis */ l = sqrt(z*z + y*y); *nx = 0; *ny = z/l; *nz = -y/l; return; } } else { if(ay < az) { /* Use Y axis */ l = sqrt(z*z + x*x); *nx = z/l; *ny = 0; *nz = -x/l; return; } } /* Use Z axis */ l = sqrt(y*y + x*x); *nx = y/l; *ny = -x/l; *nz = 0; } /* normal_vec */ /******************************************************************************* * solve_2nd_order: second order equation solve: A*t^2 + B*t + C = 0 * solve_2nd_order(&t1, NULL, A,B,C) * returns 0 if no solution was found, or set 't1' to the smallest positive * solution. * solve_2nd_order(&t1, &t2, A,B,C) * same as with &t2=NULL, but also returns the second solution. * EXAMPLE usage for intersection of a trajectory with a plane in gravitation * field (gx,gy,gz): * The neutron starts at point r=(x,y,z) with velocityv=(vx vy vz). The plane * has a normal vector n=(nx,ny,nz) and contains the point W=(wx,wy,wz). * The problem consists in solving the 2nd order equation: * 1/2.n.g.t^2 + n.v.t + n.(r-W) = 0 * so that A = 0.5 n.g; B = n.v; C = n.(r-W); * Without acceleration, t=-n.(r-W)/n.v ******************************************************************************/ int solve_2nd_order(double *t1, double *t2, double A, double B, double C) { int ret=0; if (!t1) return 0; *t1 = 0; if (t2) *t2=0; if (fabs(A) < 1E-10) /* approximate to linear equation: A ~ 0 */ { if (B) { *t1 = -C/B; ret=1; if (t2) *t2=*t1; } /* else no intersection: A=B=0 ret=0 */ } else { double D; D = B*B - 4*A*C; if (D >= 0) /* Delta > 0: two solutions */ { double sD, dt1, dt2; sD = sqrt(D); dt1 = (-B + sD)/2/A; dt2 = (-B - sD)/2/A; /* we identify very small values with zero */ if (fabs(dt1) < 1e-10) dt1=0.0; if (fabs(dt2) < 1e-10) dt2=0.0; /* now we choose the smallest positive solution */ if (dt1<=0.0 && dt2>0.0) ret=2; /* dt2 positive */ else if (dt2<=0.0 && dt1>0.0) ret=1; /* dt1 positive */ else if (dt1> 0.0 && dt2>0.0) { if (dt1 < dt2) ret=1; else ret=2; } /* all positive: min(dt1,dt2) */ /* else two solutions are negative. ret=-1 */ if (ret==1) { *t1 = dt1; if (t2) *t2=dt2; } else { *t1 = dt2; if (t2) *t2=dt1; } ret=2; /* found 2 solutions and t1 is the positive one */ } /* else Delta <0: no intersection. ret=0 */ } return(ret); } /* solve_2nd_order */ /******************************************************************************* * randvec_target_circle: Choose random direction towards target at (x,y,z) * with given radius. * If radius is zero, choose random direction in full 4PI, no target. ******************************************************************************/ void randvec_target_circle(double *xo, double *yo, double *zo, double *solid_angle, double xi, double yi, double zi, double radius) { double l2, phi, theta, nx, ny, nz, xt, yt, zt, xu, yu, zu; if(radius == 0.0) { /* No target, choose uniformly a direction in full 4PI solid angle. */ theta = acos (1 - rand0max(2)); phi = rand0max(2 * PI); if(solid_angle) *solid_angle = 4*PI; nx = 1; ny = 0; nz = 0; yi = sqrt(xi*xi+yi*yi+zi*zi); zi = 0; xi = 0; } else { double costheta0; l2 = xi*xi + yi*yi + zi*zi; /* sqr Distance to target. */ costheta0 = sqrt(l2/(radius*radius+l2)); if (radius < 0) costheta0 *= -1; if(solid_angle) { /* Compute solid angle of target as seen from origin. */ *solid_angle = 2*PI*(1 - costheta0); } /* Now choose point uniformly on circle surface within angle theta0 */ theta = acos (1 - rand0max(1 - costheta0)); /* radius on circle */ phi = rand0max(2 * PI); /* rotation on circle at given radius */ /* Now, to obtain the desired vector rotate (xi,yi,zi) angle theta around a perpendicular axis u=i x n and then angle phi around i. */ if(xi == 0 && zi == 0) { nx = 1; ny = 0; nz = 0; } else { nx = -zi; nz = xi; ny = 0; } } /* [xyz]u = [xyz]i x n[xyz] (usually vertical) */ vec_prod(xu, yu, zu, xi, yi, zi, nx, ny, nz); /* [xyz]t = [xyz]i rotated theta around [xyz]u */ rotate (xt, yt, zt, xi, yi, zi, theta, xu, yu, zu); /* [xyz]o = [xyz]t rotated phi around n[xyz] */ rotate (*xo, *yo, *zo, xt, yt, zt, phi, xi, yi, zi); } /* randvec_target_circle */ /******************************************************************************* * randvec_target_rect_angular: Choose random direction towards target at * (xi,yi,zi) with given ANGULAR dimension height x width. height=phi_x=[0,PI], * width=phi_y=[0,2*PI] (radians) * If height or width is zero, choose random direction in full 4PI, no target. *******************************************************************************/ void randvec_target_rect_angular(double *xo, double *yo, double *zo, double *solid_angle, double xi, double yi, double zi, double width, double height, Rotation A) { double theta, phi, nx, ny, nz, xt, yt, zt, xu, yu, zu; Coords tmp; Rotation Ainverse; rot_transpose(A, Ainverse); if(height == 0.0 || width == 0.0) { randvec_target_circle(xo, yo, zo, solid_angle, xi, yi, zi, 0); return; } else { if(solid_angle) { /* Compute solid angle of target as seen from origin. */ *solid_angle = 2*fabs(width*sin(height/2)); } /* Go to global coordinate system */ tmp = coords_set(xi, yi, zi); tmp = rot_apply(Ainverse, tmp); coords_get(tmp, &xi, &yi, &zi); /* Now choose point uniformly on the unit sphere segment with angle theta/phi */ phi = width*randpm1()/2.0; theta = asin(randpm1()*sin(height/2.0)); /* Now, to obtain the desired vector rotate (xi,yi,zi) angle theta around n, and then phi around u. */ if(xi == 0 && zi == 0) { nx = 1; ny = 0; nz = 0; } else { nx = -zi; nz = xi; ny = 0; } } /* [xyz]u = [xyz]i x n[xyz] (usually vertical) */ vec_prod(xu, yu, zu, xi, yi, zi, nx, ny, nz); /* [xyz]t = [xyz]i rotated theta around [xyz]u */ rotate (xt, yt, zt, xi, yi, zi, theta, nx, ny, nz); /* [xyz]o = [xyz]t rotated phi around n[xyz] */ rotate (*xo, *yo, *zo, xt, yt, zt, phi, xu, yu, zu); /* Go back to local coordinate system */ tmp = coords_set(*xo, *yo, *zo); tmp = rot_apply(A, tmp); coords_get(tmp, &*xo, &*yo, &*zo); } /* randvec_target_rect_angular */ /******************************************************************************* * randvec_target_rect_real: Choose random direction towards target at (xi,yi,zi) * with given dimension height x width (in meters !). * * Local emission coordinate is taken into account and corrected for 'order' times. * (See remarks posted to mcstas-users by George Apostolopoulus ) * * If height or width is zero, choose random direction in full 4PI, no target. * * Traditionally, this routine had the name randvec_target_rect - this is now a * a define (see mcstas-r.h) pointing here. If you use the old rouine, you are NOT * taking the local emmission coordinate into account. *******************************************************************************/ void randvec_target_rect_real(double *xo, double *yo, double *zo, double *solid_angle, double xi, double yi, double zi, double width, double height, Rotation A, double lx, double ly, double lz, int order) { double dx, dy, dist, dist_p, nx, ny, nz, mx, my, mz, n_norm, m_norm; double cos_theta; Coords tmp; Rotation Ainverse; rot_transpose(A, Ainverse); if(height == 0.0 || width == 0.0) { randvec_target_circle(xo, yo, zo, solid_angle, xi, yi, zi, 0); return; } else { /* Now choose point uniformly on rectangle within width x height */ dx = width*randpm1()/2.0; dy = height*randpm1()/2.0; /* Determine distance to target plane*/ dist = sqrt(xi*xi + yi*yi + zi*zi); /* Go to global coordinate system */ tmp = coords_set(xi, yi, zi); tmp = rot_apply(Ainverse, tmp); coords_get(tmp, &xi, &yi, &zi); /* Determine vector normal to trajectory axis (z) and gravity [0 1 0] */ vec_prod(nx, ny, nz, xi, yi, zi, 0, 1, 0); /* This now defines the x-axis, normalize: */ n_norm=sqrt(nx*nx + ny*ny + nz*nz); nx = nx/n_norm; ny = ny/n_norm; nz = nz/n_norm; /* Now, determine our y-axis (vertical in many cases...) */ vec_prod(mx, my, mz, xi, yi, zi, nx, ny, nz); m_norm=sqrt(mx*mx + my*my + mz*mz); mx = mx/m_norm; my = my/m_norm; mz = mz/m_norm; /* Our output, random vector can now be defined by linear combination: */ *xo = xi + dx * nx + dy * mx; *yo = yi + dx * ny + dy * my; *zo = zi + dx * nz + dy * mz; /* Go back to local coordinate system */ tmp = coords_set(*xo, *yo, *zo); tmp = rot_apply(A, tmp); coords_get(tmp, &*xo, &*yo, &*zo); /* Go back to local coordinate system */ tmp = coords_set(xi, yi, zi); tmp = rot_apply(A, tmp); coords_get(tmp, &xi, &yi, &zi); if (solid_angle) { /* Calculate vector from local point to remote random point */ lx = *xo - lx; ly = *yo - ly; lz = *zo - lz; dist_p = sqrt(lx*lx + ly*ly + lz*lz); /* Adjust the 'solid angle' */ /* 1/r^2 to the chosen point times cos(\theta) between the normal */ /* vector of the target rectangle and direction vector of the chosen point. */ cos_theta = (xi * lx + yi * ly + zi * lz) / (dist * dist_p); *solid_angle = width * height / (dist_p * dist_p); int counter; for (counter = 0; counter < order; counter++) { *solid_angle = *solid_angle * cos_theta; } } } } /* randvec_target_rect_real */ /* SECTION: random numbers ================================================== */ /* * Copyright (c) 1983 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* * This is derived from the Berkeley source: * @(#)random.c 5.5 (Berkeley) 7/6/88 * It was reworked for the GNU C Library by Roland McGrath. * Rewritten to use reentrant functions by Ulrich Drepper, 1995. */ /******************************************************************************* * Modified for McStas from glibc 2.0.7pre1 stdlib/random.c and * stdlib/random_r.c. * * This way random() is more than four times faster compared to calling * standard glibc random() on ix86 Linux, probably due to multithread support, * ELF shared library overhead, etc. It also makes McStas generated * simulations more portable (more likely to behave identically across * platforms, important for parrallel computations). *******************************************************************************/ #define TYPE_3 3 #define BREAK_3 128 #define DEG_3 31 #define SEP_3 3 static mc_int32_t randtbl[DEG_3 + 1] = { TYPE_3, -1726662223, 379960547, 1735697613, 1040273694, 1313901226, 1627687941, -179304937, -2073333483, 1780058412, -1989503057, -615974602, 344556628, 939512070, -1249116260, 1507946756, -812545463, 154635395, 1388815473, -1926676823, 525320961, -1009028674, 968117788, -123449607, 1284210865, 435012392, -2017506339, -911064859, -370259173, 1132637927, 1398500161, -205601318, }; static mc_int32_t *fptr = &randtbl[SEP_3 + 1]; static mc_int32_t *rptr = &randtbl[1]; static mc_int32_t *state = &randtbl[1]; #define rand_deg DEG_3 #define rand_sep SEP_3 static mc_int32_t *end_ptr = &randtbl[sizeof (randtbl) / sizeof (randtbl[0])]; mc_int32_t mc_random (void) { mc_int32_t result; *fptr += *rptr; /* Chucking least random bit. */ result = (*fptr >> 1) & 0x7fffffff; ++fptr; if (fptr >= end_ptr) { fptr = state; ++rptr; } else { ++rptr; if (rptr >= end_ptr) rptr = state; } return result; } void mc_srandom (unsigned int x) { /* We must make sure the seed is not 0. Take arbitrarily 1 in this case. */ state[0] = x ? x : 1; { long int i; for (i = 1; i < rand_deg; ++i) { /* This does: state[i] = (16807 * state[i - 1]) % 2147483647; but avoids overflowing 31 bits. */ long int hi = state[i - 1] / 127773; long int lo = state[i - 1] % 127773; long int test = 16807 * lo - 2836 * hi; state[i] = test + (test < 0 ? 2147483647 : 0); } fptr = &state[rand_sep]; rptr = &state[0]; for (i = 0; i < 10 * rand_deg; ++i) random (); } } /* "Mersenne Twister", by Makoto Matsumoto and Takuji Nishimura. */ /* See http://www.math.keio.ac.jp/~matumoto/emt.html for original source. */ /* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using mt_srandom(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any feedback is very welcome. http://www.math.keio.ac.jp/matumoto/emt.html email: matumoto@math.keio.ac.jp */ #include /* Period parameters */ #define N 624 #define M 397 #define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ static unsigned long mt[N]; /* the array for the state vector */ static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ /* initializes mt[N] with a seed */ void mt_srandom(unsigned long s) { mt[0]= s & 0xffffffffUL; for (mti=1; mti> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffffUL; /* for >32 bit machines */ } } /* initialize by an array with array-length */ /* init_key is the array for initializing keys */ /* key_length is its length */ void init_by_array(unsigned long init_key[], unsigned long key_length) { int i, j, k; mt_srandom(19650218UL); i=1; j=0; k = (N>key_length ? N : key_length); for (; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + init_key[j] + j; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=key_length) j=0; } for (k=N-1; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - i; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ } /* generates a random number on [0,0xffffffff]-interval */ unsigned long mt_random(void) { unsigned long y; static unsigned long mag01[2]={0x0UL, MATRIX_A}; /* mag01[x] = x * MATRIX_A for x=0,1 */ if (mti >= N) { /* generate N words at one time */ int kk; if (mti == N+1) /* if mt_srandom() has not been called, */ mt_srandom(5489UL); /* a default initial seed is used */ for (kk=0;kk> 1) ^ mag01[y & 0x1UL]; } for (;kk> 1) ^ mag01[y & 0x1UL]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; mti = 0; } y = mt[mti++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } #undef N #undef M #undef MATRIX_A #undef UPPER_MASK #undef LOWER_MASK /* End of "Mersenne Twister". */ /* End of McCode random number routine. */ /* randnorm: generate a random number from normal law */ double randnorm(void) { static double v1, v2, s; static int phase = 0; double X, u1, u2; if(phase == 0) { do { u1 = rand01(); u2 = rand01(); v1 = 2*u1 - 1; v2 = 2*u2 - 1; s = v1*v1 + v2*v2; } while(s >= 1 || s == 0); X = v1*sqrt(-2*log(s)/s); } else { X = v2*sqrt(-2*log(s)/s); } phase = 1 - phase; return X; } /** * Generate a random number from -1 to 1 with triangle distribution */ double randtriangle(void) { double randnum = rand01(); if (randnum>0.5) return(1-sqrt(2*(randnum-0.5))); else return(sqrt(2*randnum)-1); } /** * Random number between 0.0 and 1.0 (including?) */ double rand01() { double randnum; randnum = (double) random(); randnum /= (double) MC_RAND_MAX + 1; return randnum; } /** * Return a random number between 1 and -1 */ double randpm1() { double randnum; randnum = (double) random(); randnum /= ((double) MC_RAND_MAX + 1) / 2; randnum -= 1; return randnum; } /** * Return a random number between 0 and max. */ double rand0max(double max) { double randnum; randnum = (double) random(); randnum /= ((double) MC_RAND_MAX + 1) / max; return randnum; } /** * Return a random number between min and max. */ double randminmax(double min, double max) { return rand0max(max - min) + max; } /* SECTION: main and signal handlers ======================================== */ /******************************************************************************* * mchelp: displays instrument executable help with possible options *******************************************************************************/ static void mchelp(char *pgmname) { int i; fprintf(stderr, "%s (%s) instrument simulation, generated with " MCCODE_STRING " (" MCCODE_DATE ")\n", mcinstrument_name, mcinstrument_source); fprintf(stderr, "Usage: %s [options] [parm=value ...]\n", pgmname); fprintf(stderr, "Options are:\n" " -s SEED --seed=SEED Set random seed (must be != 0)\n" " -n COUNT --ncount=COUNT Set number of " MCCODE_PARTICLE "s to simulate.\n" " -d DIR --dir=DIR Put all data files in directory DIR.\n" " -t --trace Enable trace of " MCCODE_PARTICLE "s through instrument.\n" " -g --gravitation Enable gravitation for all trajectories.\n" " --no-output-files Do not write any data files.\n" " -h --help Show this help message.\n" " -i --info Detailed instrument information.\n" " --format=FORMAT Output data files using FORMAT=" FLAVOR_UPPER #ifdef USE_NEXUS " NEXUS" #endif "\n\n" ); #ifdef USE_MPI fprintf(stderr, "This instrument has been compiled with MPI support.\n Use 'mpirun %s [options] [parm=value ...]'.\n", pgmname); #endif if(mcnumipar > 0) { fprintf(stderr, "Instrument parameters are:\n"); for(i = 0; i < mcnumipar; i++) if (mcinputtable[i].val && strlen(mcinputtable[i].val)) fprintf(stderr, " %-16s(%s) [default='%s']\n", mcinputtable[i].name, (*mcinputtypes[mcinputtable[i].type].parminfo)(mcinputtable[i].name), mcinputtable[i].val); else fprintf(stderr, " %-16s(%s)\n", mcinputtable[i].name, (*mcinputtypes[mcinputtable[i].type].parminfo)(mcinputtable[i].name)); } #ifndef NOSIGNALS fprintf(stderr, "Known signals are: " #ifdef SIGUSR1 "USR1 (status) " #endif #ifdef SIGUSR2 "USR2 (save) " #endif #ifdef SIGBREAK "BREAK (save) " #endif #ifdef SIGTERM "TERM (save and exit)" #endif "\n"); #endif /* !NOSIGNALS */ } /* mchelp */ /* mcshowhelp: show help and exit with 0 */ static void mcshowhelp(char *pgmname) { mchelp(pgmname); exit(0); } /* mcusage: display usage when error in input arguments and exit with 1 */ static void mcusage(char *pgmname) { fprintf(stderr, "Error: incorrect command line arguments\n"); mchelp(pgmname); exit(1); } /* mcenabletrace: enable trace/mcdisplay or error if requires recompile */ static void mcenabletrace(void) { if(mctraceenabled) mcdotrace = 1; else { fprintf(stderr, "Error: trace not enabled (mcenabletrace)\n" "Please re-run the " MCCODE_NAME " compiler " "with the --trace option, or rerun the\n" "C compiler with the MC_TRACE_ENABLED macro defined.\n"); exit(1); } } /******************************************************************************* * mcreadparams: request parameters from the prompt (or use default) *******************************************************************************/ void mcreadparams(void) { int i,j,status; static char buf[CHAR_BUF_LENGTH]; char *p; int len; MPI_MASTER(printf("Instrument parameters for %s (%s)\n", mcinstrument_name, mcinstrument_source)); for(i = 0; mcinputtable[i].name != 0; i++) { do { MPI_MASTER( if (mcinputtable[i].val && strlen(mcinputtable[i].val)) printf("Set value of instrument parameter %s (%s) [default='%s']:\n", mcinputtable[i].name, (*mcinputtypes[mcinputtable[i].type].parminfo) (mcinputtable[i].name), mcinputtable[i].val); else printf("Set value of instrument parameter %s (%s):\n", mcinputtable[i].name, (*mcinputtypes[mcinputtable[i].type].parminfo) (mcinputtable[i].name)); fflush(stdout); ); #ifdef USE_MPI if(mpi_node_rank == mpi_node_root) { p = fgets(buf, CHAR_BUF_LENGTH, stdin); if(p == NULL) { fprintf(stderr, "Error: empty input for paramater %s (mcreadparams)\n", mcinputtable[i].name); exit(1); } } else p = buf; MPI_Bcast(buf, CHAR_BUF_LENGTH, MPI_CHAR, mpi_node_root, MPI_COMM_WORLD); #else /* !USE_MPI */ p = fgets(buf, CHAR_BUF_LENGTH, stdin); if(p == NULL) { fprintf(stderr, "Error: empty input for paramater %s (mcreadparams)\n", mcinputtable[i].name); exit(1); } #endif /* USE_MPI */ len = strlen(buf); if (!len || (len == 1 && (buf[0] == '\n' || buf[0] == '\r'))) { if (mcinputtable[i].val && strlen(mcinputtable[i].val)) { strncpy(buf, mcinputtable[i].val, CHAR_BUF_LENGTH); /* use default value */ len = strlen(buf); } } for(j = 0; j < 2; j++) { if(len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r')) { len--; buf[len] = '\0'; } } status = (*mcinputtypes[mcinputtable[i].type].getparm) (buf, mcinputtable[i].par); if(!status) { (*mcinputtypes[mcinputtable[i].type].error)(mcinputtable[i].name, buf); if (!mcinputtable[i].val || strlen(mcinputtable[i].val)) { fprintf(stderr, " Change %s default value in instrument definition.\n", mcinputtable[i].name); exit(1); } } } while(!status); } } /* mcreadparams */ /******************************************************************************* * mcparseoptions: parse command line arguments (options, parameters) *******************************************************************************/ void mcparseoptions(int argc, char *argv[]) { int i, j; char *p; int paramset = 0, *paramsetarray; char *usedir=NULL; /* Add one to mcnumipar to avoid allocating zero size memory block. */ paramsetarray = (int*)malloc((mcnumipar + 1)*sizeof(*paramsetarray)); if(paramsetarray == NULL) { fprintf(stderr, "Error: insufficient memory (mcparseoptions)\n"); exit(1); } for(j = 0; j < mcnumipar; j++) { paramsetarray[j] = 0; if (mcinputtable[j].val != NULL && strlen(mcinputtable[j].val)) { int status; char buf[CHAR_BUF_LENGTH]; strncpy(buf, mcinputtable[j].val, CHAR_BUF_LENGTH); status = (*mcinputtypes[mcinputtable[j].type].getparm) (buf, mcinputtable[j].par); if(!status) fprintf(stderr, "Invalid '%s' default value %s in instrument definition (mcparseoptions)\n", mcinputtable[j].name, buf); else paramsetarray[j] = 1; } else { (*mcinputtypes[mcinputtable[j].type].getparm) (NULL, mcinputtable[j].par); paramsetarray[j] = 0; } } for(i = 1; i < argc; i++) { if(!strcmp("-s", argv[i]) && (i + 1) < argc) mcsetseed(argv[++i]); else if(!strncmp("-s", argv[i], 2)) mcsetseed(&argv[i][2]); else if(!strcmp("--seed", argv[i]) && (i + 1) < argc) mcsetseed(argv[++i]); else if(!strncmp("--seed=", argv[i], 7)) mcsetseed(&argv[i][7]); else if(!strcmp("-n", argv[i]) && (i + 1) < argc) mcsetn_arg(argv[++i]); else if(!strncmp("-n", argv[i], 2)) mcsetn_arg(&argv[i][2]); else if(!strcmp("--ncount", argv[i]) && (i + 1) < argc) mcsetn_arg(argv[++i]); else if(!strncmp("--ncount=", argv[i], 9)) mcsetn_arg(&argv[i][9]); else if(!strcmp("-d", argv[i]) && (i + 1) < argc) usedir=argv[++i]; /* will create directory after parsing all arguments (end of this function) */ else if(!strncmp("-d", argv[i], 2)) usedir=&argv[i][2]; else if(!strcmp("--dir", argv[i]) && (i + 1) < argc) usedir=argv[++i]; else if(!strncmp("--dir=", argv[i], 6)) usedir=&argv[i][6]; else if(!strcmp("-h", argv[i])) mcshowhelp(argv[0]); else if(!strcmp("--help", argv[i])) mcshowhelp(argv[0]); else if(!strcmp("-i", argv[i])) { mcformat=FLAVOR_UPPER; mcinfo(); } else if(!strcmp("--info", argv[i])) mcinfo(); else if(!strcmp("-t", argv[i])) mcenabletrace(); else if(!strcmp("--trace", argv[i])) mcenabletrace(); else if(!strcmp("--gravitation", argv[i])) mcgravitation = 1; else if(!strcmp("-g", argv[i])) mcgravitation = 1; else if(!strncmp("--format=", argv[i], 9)) { mcformat=&argv[i][9]; } else if(!strcmp("--format", argv[i]) && (i + 1) < argc) { mcformat=argv[++i]; } else if(!strcmp("--no-output-files", argv[i])) mcdisable_output_files = 1; else if(argv[i][0] != '-' && (p = strchr(argv[i], '=')) != NULL) { *p++ = '\0'; for(j = 0; j < mcnumipar; j++) if(!strcmp(mcinputtable[j].name, argv[i])) { int status; status = (*mcinputtypes[mcinputtable[j].type].getparm)(p, mcinputtable[j].par); if(!status || !strlen(p)) { (*mcinputtypes[mcinputtable[j].type].error) (mcinputtable[j].name, p); exit(1); } paramsetarray[j] = 1; paramset = 1; break; } if(j == mcnumipar) { /* Unrecognized parameter name */ fprintf(stderr, "Error: unrecognized parameter %s (mcparseoptions)\n", argv[i]); exit(1); } } else if(argv[i][0] == '-') { fprintf(stderr, "Error: unrecognized option argument %s (mcparseoptions). Ignored.\n", argv[i++]); } else { fprintf(stderr, "Error: unrecognized argument %s (mcparseoptions). Aborting.\n", argv[i]); mcusage(argv[0]); } } if(!paramset) mcreadparams(); /* Prompt for parameters if not specified. */ else { for(j = 0; j < mcnumipar; j++) if(!paramsetarray[j]) { fprintf(stderr, "Error: Instrument parameter %s left unset (mcparseoptions)\n", mcinputtable[j].name); exit(1); } } free(paramsetarray); #ifdef USE_MPI if (mcdotrace) mpi_node_count=1; /* disable threading when in trace mode */ #endif if (usedir && strlen(usedir)) mcuse_dir(usedir); } /* mcparseoptions */ #ifndef NOSIGNALS mcstatic char mcsig_message[256]; /******************************************************************************* * sighandler: signal handler that makes simulation stop, and save results *******************************************************************************/ void sighandler(int sig) { /* MOD: E. Farhi, Sep 20th 2001: give more info */ time_t t1, t0; #define SIG_SAVE 0 #define SIG_TERM 1 #define SIG_STAT 2 #define SIG_ABRT 3 printf("\n# " MCCODE_STRING ": [pid %i] Signal %i detected", getpid(), sig); #ifdef USE_MPI printf(" [proc %i]", mpi_node_rank); #endif #if defined(SIGUSR1) && defined(SIGUSR2) && defined(SIGKILL) if (!strcmp(mcsig_message, "sighandler") && (sig != SIGUSR1) && (sig != SIGUSR2)) { printf("\n# Fatal : unrecoverable loop ! Suicide (naughty boy).\n"); kill(0, SIGKILL); /* kill myself if error occurs within sighandler: loops */ } #endif switch (sig) { #ifdef SIGINT case SIGINT : printf(" SIGINT (interrupt from terminal, Ctrl-C)"); sig = SIG_TERM; break; #endif #ifdef SIGILL case SIGILL : printf(" SIGILL (Illegal instruction)"); sig = SIG_ABRT; break; #endif #ifdef SIGFPE case SIGFPE : printf(" SIGFPE (Math Error)"); sig = SIG_ABRT; break; #endif #ifdef SIGSEGV case SIGSEGV : printf(" SIGSEGV (Mem Error)"); sig = SIG_ABRT; break; #endif #ifdef SIGTERM case SIGTERM : printf(" SIGTERM (Termination)"); sig = SIG_TERM; break; #endif #ifdef SIGABRT case SIGABRT : printf(" SIGABRT (Abort)"); sig = SIG_ABRT; break; #endif #ifdef SIGQUIT case SIGQUIT : printf(" SIGQUIT (Quit from terminal)"); sig = SIG_TERM; break; #endif #ifdef SIGTRAP case SIGTRAP : printf(" SIGTRAP (Trace trap)"); sig = SIG_ABRT; break; #endif #ifdef SIGPIPE case SIGPIPE : printf(" SIGPIPE (Broken pipe)"); sig = SIG_ABRT; break; #endif #ifdef SIGUSR1 case SIGUSR1 : printf(" SIGUSR1 (Display info)"); sig = SIG_STAT; break; #endif #ifdef SIGUSR2 case SIGUSR2 : printf(" SIGUSR2 (Save simulation)"); sig = SIG_SAVE; break; #endif #ifdef SIGHUP case SIGHUP : printf(" SIGHUP (Hangup/update)"); sig = SIG_SAVE; break; #endif #ifdef SIGBUS case SIGBUS : printf(" SIGBUS (Bus error)"); sig = SIG_ABRT; break; #endif #ifdef SIGURG case SIGURG : printf(" SIGURG (Urgent socket condition)"); sig = SIG_ABRT; break; #endif #ifdef SIGBREAK case SIGBREAK: printf(" SIGBREAK (Break signal, Ctrl-Break)"); sig = SIG_SAVE; break; #endif default : printf(" (look at signal list for signification)"); sig = SIG_ABRT; break; } printf("\n"); printf("# Simulation: %s (%s) \n", mcinstrument_name, mcinstrument_source); printf("# Breakpoint: %s ", mcsig_message); if (strstr(mcsig_message, "Save") && (sig == SIG_SAVE)) sig = SIG_STAT; SIG_MESSAGE("sighandler"); if (mcget_ncount() == 0) printf("(0 %%)\n" ); else { printf("%.2f %% (%10.1f/%10.1f)\n", 100.0*mcget_run_num()/mcget_ncount(), 1.0*mcget_run_num(), 1.0*mcget_ncount()); } t0 = (time_t)mcstartdate; t1 = time(NULL); printf("# Date: %s", ctime(&t1)); printf("# Started: %s", ctime(&t0)); if (sig == SIG_STAT) { printf("# " MCCODE_STRING ": Resuming simulation (continue)\n"); fflush(stdout); return; } else if (sig == SIG_SAVE) { printf("# " MCCODE_STRING ": Saving data and resume simulation (continue)\n"); mcsave(NULL); fflush(stdout); return; } else if (sig == SIG_TERM) { printf("# " MCCODE_STRING ": Finishing simulation (save results and exit)\n"); mcfinally(); exit(0); } else { fflush(stdout); perror("# Last I/O Error"); printf("# " MCCODE_STRING ": Simulation stop (abort).\n"); // This portion of the signal handling only works on UNIX #if defined(__unix__) || defined(__APPLE__) signal(sig, SIG_DFL); /* force to use default sighandler now */ kill(getpid(), sig); /* and trigger it with the current signal */ #endif exit(-1); } #undef SIG_SAVE #undef SIG_TERM #undef SIG_STAT #undef SIG_ABRT } /* sighandler */ #endif /* !NOSIGNALS */ /******************************************************************************* * mccode_main: McCode main() function. *******************************************************************************/ int mccode_main(int argc, char *argv[]) { /* double run_num = 0; */ time_t t; #ifdef USE_MPI char mpi_node_name[MPI_MAX_PROCESSOR_NAME]; int mpi_node_name_len; #endif /* USE_MPI */ #ifdef MAC argc = ccommand(&argv); #endif #ifdef USE_MPI MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD, &mpi_node_count); /* get number of nodes */ MPI_Comm_rank(MPI_COMM_WORLD, &mpi_node_rank); MPI_Comm_set_name(MPI_COMM_WORLD, mcinstrument_name); MPI_Get_processor_name(mpi_node_name, &mpi_node_name_len); #endif /* USE_MPI */ t = time(NULL); mcseed = (long)t+(long)getpid(); #ifdef USE_MPI /* *** print number of nodes *********************************************** */ if (mpi_node_count > 1) { MPI_MASTER( printf("Simulation '%s' (%s): running on %i nodes (master is '%s', MPI version %i.%i).\n", mcinstrument_name, mcinstrument_source, mpi_node_count, mpi_node_name, MPI_VERSION, MPI_SUBVERSION); ); } #endif /* USE_MPI */ mcstartdate = (long)t; /* set start date before parsing options and creating sim file */ /* *** parse options ******************************************************* */ SIG_MESSAGE("main (Start)"); mcformat=getenv(FLAVOR_UPPER "_FORMAT") ? getenv(FLAVOR_UPPER "_FORMAT") : FLAVOR_UPPER; mcinstrument_exe = argv[0]; /* store the executable path */ /* read simulation parameters and options */ mcparseoptions(argc, argv); /* sets output dir and format */ #ifdef USE_MPI if (mpi_node_count > 1) { /* share the same seed, then adapt random seed for each node */ MPI_Bcast(&mcseed, 1, MPI_LONG, 0, MPI_COMM_WORLD); /* root sends its seed to slaves */ mcseed += mpi_node_rank; /* make sure we use different seeds per node */ } #endif srandom(mcseed); /* *** install sig handler, but only once !! after parameters parsing ******* */ #ifndef NOSIGNALS #ifdef SIGQUIT if (signal( SIGQUIT ,sighandler) == SIG_IGN) signal( SIGQUIT,SIG_IGN); /* quit (ASCII FS) */ #endif #ifdef SIGABRT if (signal( SIGABRT ,sighandler) == SIG_IGN) signal( SIGABRT,SIG_IGN); /* used by abort, replace SIGIOT in the future */ #endif #ifdef SIGTERM if (signal( SIGTERM ,sighandler) == SIG_IGN) signal( SIGTERM,SIG_IGN); /* software termination signal from kill */ #endif #ifdef SIGUSR1 if (signal( SIGUSR1 ,sighandler) == SIG_IGN) signal( SIGUSR1,SIG_IGN); /* display simulation status */ #endif #ifdef SIGUSR2 if (signal( SIGUSR2 ,sighandler) == SIG_IGN) signal( SIGUSR2,SIG_IGN); #endif #ifdef SIGHUP if (signal( SIGHUP ,sighandler) == SIG_IGN) signal( SIGHUP,SIG_IGN); #endif #ifdef SIGILL if (signal( SIGILL ,sighandler) == SIG_IGN) signal( SIGILL,SIG_IGN); /* illegal instruction (not reset when caught) */ #endif #ifdef SIGFPE if (signal( SIGFPE ,sighandler) == SIG_IGN) signal( SIGSEGV,SIG_IGN); /* floating point exception */ #endif #ifdef SIGBUS if (signal( SIGBUS ,sighandler) == SIG_IGN) signal( SIGSEGV,SIG_IGN); /* bus error */ #endif #ifdef SIGSEGV if (signal( SIGSEGV ,sighandler) == SIG_IGN) signal( SIGSEGV,SIG_IGN); /* segmentation violation */ #endif #endif /* !NOSIGNALS */ mcsiminfo_init(NULL); /* open SIM */ SIG_MESSAGE("main (Init)"); mcinit(); #ifndef NOSIGNALS #ifdef SIGINT if (signal( SIGINT ,sighandler) == SIG_IGN) signal( SIGINT,SIG_IGN); /* interrupt (rubout) only after INIT */ #endif #endif /* !NOSIGNALS */ /* ================ main particle generation/propagation loop ================ */ #if defined (USE_MPI) /* sliced Ncount on each MPI node */ mcncount = mpi_node_count > 1 ? floor(mcncount / mpi_node_count) : mcncount; /* number of rays per node */ #endif /* main particle event loop */ while(mcrun_num < mcncount || mcrun_num < mcget_ncount()) { #ifndef NEUTRONICS mcgenstate(); #endif /* old init: mcsetstate(0, 0, 0, 0, 0, 1, 0, sx=0, sy=1, sz=0, 1); */ mcraytrace(); mcrun_num++; } #ifdef USE_MPI /* merge run_num from MPI nodes */ if (mpi_node_count > 1) { double mcrun_num_double = (double)mcrun_num; mc_MPI_Sum(&mcrun_num_double, 1); mcrun_num = (unsigned long long)mcrun_num_double; } #endif /* save/finally executed by master node/thread */ mcfinally(); #ifdef USE_MPI MPI_Finalize(); #endif /* USE_MPI */ return 0; } /* mccode_main */ #ifdef NEUTRONICS /*Main neutronics function steers the McStas calls, initializes parameters etc */ /* Only called in case NEUTRONICS = TRUE */ void neutronics_main_(float *inx, float *iny, float *inz, float *invx, float *invy, float *invz, float *intime, float *insx, float *insy, float *insz, float *inw, float *outx, float *outy, float *outz, float *outvx, float *outvy, float *outvz, float *outtime, float *outsx, float *outsy, float *outsz, float *outwgt) { extern double mcnx, mcny, mcnz, mcnvx, mcnvy, mcnvz; extern double mcnt, mcnsx, mcnsy, mcnsz, mcnp; /* External code governs iteration - McStas is iterated once per call to neutronics_main. I.e. below counter must be initiancated for each call to neutronics_main*/ mcrun_num=0; time_t t; t = (time_t)mcstartdate; mcstartdate = t; /* set start date before parsing options and creating sim file */ mcinit(); /* *** parse options *** */ SIG_MESSAGE("main (Start)"); mcformat=getenv(FLAVOR_UPPER "_FORMAT") ? getenv(FLAVOR_UPPER "_FORMAT") : FLAVOR_UPPER; /* Set neutron state based on input from neutronics code */ mcsetstate(*inx,*iny,*inz,*invx,*invy,*invz,*intime,*insx,*insy,*insz,*inw); /* main neutron event loop - runs only one iteration */ //mcstas_raytrace(&mcncount); /* prior to McStas 1.12 */ mcallowbackprop = 1; //avoid absorbtion from negative dt int argc=1; char *argv[0]; int dummy = mccode_main(argc, argv); *outx = mcnx; *outy = mcny; *outz = mcnz; *outvx = mcnvx; *outvy = mcnvy; *outvz = mcnvz; *outtime = mcnt; *outsx = mcnsx; *outsy = mcnsy; *outsz = mcnsz; *outwgt = mcnp; return; } /* neutronics_main */ #endif /*NEUTRONICS*/ #endif /* !MCCODE_H */ /* End of file "mccode-r.c". */ /* End of file "mccode-r.c". */ #line 4855 "tof_diffraction.c" #line 1 "mcstas-r.c" /******************************************************************************* * * McStas, neutron ray-tracing package * Copyright (C) 1997-2009, All rights reserved * Risoe National Laboratory, Roskilde, Denmark * Institut Laue Langevin, Grenoble, France * * Runtime: share/mcstas-r.c * * %Identification * Written by: KN * Date: Aug 29, 1997 * Release: McStas X.Y * Version: $Revision$ * * Runtime system for McStas. * Embedded within instrument in runtime mode. * * Usage: Automatically embbeded in the c code whenever required. * * $Id$ * *******************************************************************************/ #ifndef MCSTAS_R_H #include "mcstas-r.h" #endif #ifdef DANSE #include "mcstas-globals.h" #endif /******************************************************************************* * The I/O format definitions and functions *******************************************************************************/ /*the magnet stack*/ #ifdef MC_POL_COMPAT void (*mcMagnetPrecession) (double, double, double, double, double, double, double, double*, double*, double*, double, Coords, Rotation)=NULL; Coords mcMagnetPos; Rotation mcMagnetRot; double* mcMagnetData = NULL; /* mcMagneticField(x, y, z, t, Bx, By, Bz) */ int (*mcMagneticField) (double, double, double, double, double*, double*, double*, void *) = NULL; #endif #ifndef MCSTAS_H /******************************************************************************* * mcstore_neutron: stores neutron coodinates into global array (per component) *******************************************************************************/ void mcstore_neutron(MCNUM *s, int index, double x, double y, double z, double vx, double vy, double vz, double t, double sx, double sy, double sz, double p) { double *dptr = &s[11*index]; *dptr++ = x; *dptr++ = y ; *dptr++ = z ; *dptr++ = vx; *dptr++ = vy; *dptr++ = vz; *dptr++ = t ; *dptr++ = sx; *dptr++ = sy; *dptr++ = sz; *dptr = p ; } /* mcstore_neutron */ /******************************************************************************* * mcrestore_neutron: restores neutron coodinates from global array *******************************************************************************/ void mcrestore_neutron(MCNUM *s, int index, double *x, double *y, double *z, double *vx, double *vy, double *vz, double *t, double *sx, double *sy, double *sz, double *p) { double *dptr = &s[11*index]; *x = *dptr++; *y = *dptr++; *z = *dptr++; *vx = *dptr++; *vy = *dptr++; *vz = *dptr++; *t = *dptr++; *sx = *dptr++; *sy = *dptr++; *sz = *dptr++; *p = *dptr; } /* mcrestore_neutron */ /******************************************************************************* * mcsetstate: transfer parameters into global McStas variables *******************************************************************************/ void mcsetstate(double x, double y, double z, double vx, double vy, double vz, double t, double sx, double sy, double sz, double p) { extern double mcnx, mcny, mcnz, mcnvx, mcnvy, mcnvz; extern double mcnt, mcnsx, mcnsy, mcnsz, mcnp; mcnx = x; mcny = y; mcnz = z; mcnvx = vx; mcnvy = vy; mcnvz = vz; mcnt = t; mcnsx = sx; mcnsy = sy; mcnsz = sz; mcnp = p; } /* mcsetstate */ /******************************************************************************* * mcgenstate: set default neutron parameters *******************************************************************************/ void mcgenstate(void) { mcsetstate(0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); /* old initialisation: mcsetstate(0, 0, 0, 0, 0, 1, 0, sx=0, sy=1, sz=0, 1); */ } /* intersection routines ==================================================== */ /******************************************************************************* * inside_rectangle: Check if (x,y) is inside rectangle (xwidth, yheight) * return 0 if outside and 1 if inside *******************************************************************************/ int inside_rectangle(double x, double y, double xwidth, double yheight) { if (x>-xwidth/2 && x-yheight/2 && y -dy/2 && y_in < dy/2 && z_in > -dz/2 && z_in < dz/2) t[0] = tt; else t[0] = 0; tt = (dx/2 - x)/vx; y_in = y + tt*vy; z_in = z + tt*vz; if( y_in > -dy/2 && y_in < dy/2 && z_in > -dz/2 && z_in < dz/2) t[1] = tt; else t[1] = 0; } else t[0] = t[1] = 0; if(vy != 0) { tt = -(dy/2 + y)/vy; x_in = x + tt*vx; z_in = z + tt*vz; if( x_in > -dx/2 && x_in < dx/2 && z_in > -dz/2 && z_in < dz/2) t[2] = tt; else t[2] = 0; tt = (dy/2 - y)/vy; x_in = x + tt*vx; z_in = z + tt*vz; if( x_in > -dx/2 && x_in < dx/2 && z_in > -dz/2 && z_in < dz/2) t[3] = tt; else t[3] = 0; } else t[2] = t[3] = 0; if(vz != 0) { tt = -(dz/2 + z)/vz; x_in = x + tt*vx; y_in = y + tt*vy; if( x_in > -dx/2 && x_in < dx/2 && y_in > -dy/2 && y_in < dy/2) t[4] = tt; else t[4] = 0; tt = (dz/2 - z)/vz; x_in = x + tt*vx; y_in = y + tt*vy; if( x_in > -dx/2 && x_in < dx/2 && y_in > -dy/2 && y_in < dy/2) t[5] = tt; else t[5] = 0; } else t[4] = t[5] = 0; /* The intersection is evaluated and *dt_in and *dt_out are assigned */ a = b = s = 0; count = 0; for( i = 0; i < 6; i = i + 1 ) if( t[i] == 0 ) s = s+1; else if( count == 0 ) { a = t[i]; count = 1; } else { b = t[i]; count = 2; } if ( a == 0 && b == 0 ) return 0; else if( a < b ) { *dt_in = a; *dt_out = b; return 1; } else { *dt_in = b; *dt_out = a; return 1; } } /* box_intersect */ /******************************************************************************* * cylinder_intersect: compute intersection with a cylinder * returns 0 when no intersection is found * or 2/4/8/16 bits depending on intersection, * and resulting times t0 and t1 * Written by: EM,NB,ABA 4.2.98 *******************************************************************************/ int cylinder_intersect(double *t0, double *t1, double x, double y, double z, double vx, double vy, double vz, double r, double h) { double D, t_in, t_out, y_in, y_out; int ret=1; D = (2*vx*x + 2*vz*z)*(2*vx*x + 2*vz*z) - 4*(vx*vx + vz*vz)*(x*x + z*z - r*r); if (D>=0) { if (vz*vz + vx*vx) { t_in = (-(2*vz*z + 2*vx*x) - sqrt(D))/(2*(vz*vz + vx*vx)); t_out = (-(2*vz*z + 2*vx*x) + sqrt(D))/(2*(vz*vz + vx*vx)); } else if (vy) { /* trajectory parallel to cylinder axis */ t_in = (-h/2-y)/vy; t_out = (h/2-y)/vy; if (t_in>t_out){ double tmp=t_in; t_in=t_out;t_out=tmp; } } else return 0; y_in = vy*t_in + y; y_out =vy*t_out + y; if ( (y_in > h/2 && y_out > h/2) || (y_in < -h/2 && y_out < -h/2) ) return 0; else { if (y_in > h/2) { t_in = ((h/2)-y)/vy; ret += 2; } else if (y_in < -h/2) { t_in = ((-h/2)-y)/vy; ret += 4; } if (y_out > h/2) { t_out = ((h/2)-y)/vy; ret += 8; } else if (y_out < -h/2) { t_out = ((-h/2)-y)/vy; ret += 16; } } *t0 = t_in; *t1 = t_out; return ret; } else { *t0 = *t1 = 0; return 0; } } /* cylinder_intersect */ /******************************************************************************* * sphere_intersect: Calculate intersection between a line and a sphere. * returns 0 when no intersection is found * or 1 in case of intersection with resulting times t0 and t1 *******************************************************************************/ int sphere_intersect(double *t0, double *t1, double x, double y, double z, double vx, double vy, double vz, double r) { double A, B, C, D, v; v = sqrt(vx*vx + vy*vy + vz*vz); A = v*v; B = 2*(x*vx + y*vy + z*vz); C = x*x + y*y + z*z - r*r; D = B*B - 4*A*C; if(D < 0) return 0; D = sqrt(D); *t0 = (-B - D) / (2*A); *t1 = (-B + D) / (2*A); return 1; } /* sphere_intersect */ /******************************************************************************* * plane_intersect: Calculate intersection between a plane and a line. * returns 0 when no intersection is found (i.e. line is parallel to the plane) * returns 1 or -1 when intersection time is positive and negative respectively *******************************************************************************/ int plane_intersect(double *t, double x, double y, double z, double vx, double vy, double vz, double nx, double ny, double nz, double wx, double wy, double wz) { double s; if (fabs(s=scalar_prod(nx,ny,nz,vx,vy,vz))testDiff) { ns=i; diff=testDiff; } C[i]=Y[i]; D[i]=Y[i]; } out=Y[ns]; ns--; /* Now can be -1 !!!! */ for(m=1;mAR[Npts-1]) return Npts; if(AR[0]>0.0)AR[0]=0.0; if (V0.0)AR[0]=0.0; fprintf(stderr,"here"); return 0; } klo=0; khi= Npts-1; while (khi-klo >1) { k=(khi+klo) >> 1; // quick division by 2 if (AR[k]>V) khi=k; else klo=k; } return khi; } int cmdnumberD(char *mc,double* num) /*! \returns 1 on success 0 on failure */ { int i,j; char* ss; char **endptr; double nmb; int len; len=strlen(mc); j=0; for(i=0;iEinit && *Ea Eb that is encompassed by EI->EE */ { double frac; double dRange; if (EI>Eb) return 0.0; if (EEEa) ? (Eb-EI)/dRange : 1.0; frac-=(EE Eend \param Einit :: inital Energy \parma Eend :: final energy */ { char ss[255]; /* BIG space for line */ double Ea,Eb; double T,D; double Efrac; // Fraction of an Energy Bin int Ftime; // time Flag int eIndex; // energy Index int tIndex; // time Index double Tsum; // Running integration double Efraction; // Amount to use for an energy/time bin // extern Source TS; int DebugCnt; int i; /*! Status Flag:: Ftime=1 :: [time ] Reading Time : Data : Err [Exit on Total] /* Double Read File to determine how many bins and memery size */ if (!TFile) return(0); Ea=0.0; Eb=0.0; fprintf(stderr,"Energy == %g %g\n",Einit,Eend); eIndex= -1; DebugCnt=0; Ftime=0; tIndex=0; TS->nTime=0; TS->nEnergy=0; // Read file and get time bins while(fgets(ss,255,TFile) && Eend>Ea) { if (notComment(ss)) { DebugCnt++; if (!Ftime) { if (energyBin(ss,Einit,Eend,&Ea,&Eb)) { if (eIndex==0) TS->nTime=tIndex; eIndex++; } else if (timeStart(ss)) { Ftime=1; tIndex=0; } } else // In the time section { if (timeEnd(ss)) // Found "total" Ftime=0; else { // Need to read the line in the case of first run if (TS->nTime==0) { if (cmdnumberD(ss,&T) && cmdnumberD(ss,&D)) tIndex++; } } } } } // Plus 2 since we have a 0 counter and we have missed the last line. TS->nEnergy=eIndex+2; if (!TS->nTime && tIndex) TS->nTime=tIndex; // printf("tIndex %d %d %d %d \n",tIndex,eIndex,TS->nEnergy,TS->nTime); /* SECOND TIME THROUGH:: */ rewind(TFile); TS->Flux=matrix(TS->nEnergy,TS->nTime); TS->EInt=(double*) malloc(TS->nEnergy*sizeof(double)); TS->TimeBin=(double*) malloc(TS->nTime*sizeof(double)); TS->EnergyBin=(double*) malloc(TS->nEnergy*sizeof(double)); Tsum=0.0; Ea=0.0; Eb=0.0; eIndex=-1; DebugCnt=0; Ftime=0; tIndex=0; TS->EInt[0]=0.0; // Read file and get time bins while(fgets(ss,255,TFile) && Eend>Ea) { if (notComment(ss)) { DebugCnt++; if (!Ftime) { if (energyBin(ss,Einit,Eend,&Ea,&Eb)) { eIndex++; TS->EnergyBin[eIndex]=(Einit>Ea) ? Einit : Ea; Efraction=calcFraction(Einit,Eend,Ea,Eb); Ftime++; } } else if (Ftime==1) { if (timeStart(ss)) { Ftime=2; tIndex=0; } } else // In the time section { if (timeEnd(ss)) // Found "total" { Ftime=0; TS->EInt[eIndex+1]=Tsum; } else { // Need to read the line in the case of first run if (cmdnumberD(ss,&T) && cmdnumberD(ss,&D)) { TS->TimeBin[tIndex]=T/1e8; // convert Time into second (from shakes) Tsum+=D*Efraction; TS->Flux[eIndex][tIndex]=Tsum; tIndex++; } } } } } TS->EnergyBin[eIndex+1]=Eend; TS->Total=Tsum; // printf("tIndex %d %d %d \n",tIndex,eIndex,TS.nTime); //printf("Tsum %g \n",Tsum); //fprintf(stderr,"ebin1 ebinN %g %g\n",TS.EnergyBin[0],TS.EnergyBin[TS.nEnergy-1]); return 1; } // readHtable void getPoint(double* TV,double* EV,double* lim1, double* lim2, Source TS) /*! Calculate the Time and Energy by sampling the file. Uses TS table to find the point \param TV :: \param EV :: \param lim1 :: \param lim2 :: */ { int i; // extern Source TS; double R0,R1,R,Rend; int Epnt; ///< Points to the next higher index of the neutron integral int Tpnt; int iStart,iEnd; double TRange,Tspread; double Espread,Estart; double *EX; // So that lowPoly+highPoly==maxPoly const int maxPoly=6; const int highPoly=maxPoly/2; const int lowPoly=maxPoly-highPoly; // static int testVar=0; R0=rand01(); /* if (testVar==0) { R0=1.0e-8; testVar=1; } */ Rend=R=TS.Total*R0; // This gives Eint[Epnt-1] > R > Eint[Epnt] Epnt=binSearch(TS.nEnergy-1,TS.EInt,R); // if (Epnt < 0) // Epnt=1; Tpnt=binSearch(TS.nTime-1,TS.Flux[Epnt-1],R); // fprintf(stderr,"TBoundaryX == %12.6e %12.6e \n",TS.TimeBin[Tpnt-1],TS.TimeBin[Tpnt]); // fprintf(stderr,"TFlux == %12.6e %12.6e %12.6e \n\n",TS.Flux[Epnt-1][Tpnt-1],R,TS.Flux[Epnt-1][Tpnt]); // if (Epnt == -1) //{ // Epnt=0; // fprintf(stderr,"\n Rvals == %g %d %d %g\n",R,Epnt,Tpnt,TS.TimeBin[0]); // fprintf(stderr,"EInt == %d %12.6e %12.6e %12.6e %12.6e \n",Epnt,TS.EInt[Epnt-1],R,TS.EInt[Epnt],TS.EInt[Epnt+1]); // printf("EBoundary == %12.6e %12.6e \n",TS.EnergyBin[Epnt],TS.EnergyBin[Epnt+1]); // fprintf(stderr,"TFlux == %12.6e %12.6e %12.6e \n\n",TS.Flux[Epnt+1][Tpnt],R,TS.Flux[Epnt+1][Tpnt+1]); // } if(R < TS.Flux[Epnt-1][Tpnt-1] || R >TS.Flux[Epnt-1][Tpnt] ) { fprintf(stderr,"outside bin limits Tpnt/Epnt problem %12.6e %12.6e %12.6e \n",TS.Flux[Epnt-1][Tpnt-1],R,TS.Flux[Epnt-1][Tpnt]); } if(Epnt == 0) { Estart=0.0; Espread=TS.EInt[0]; *EV=TS.EnergyBin[1]; } else { Estart=TS.EInt[Epnt-1]; Espread=TS.EInt[Epnt]-TS.EInt[Epnt-1]; *EV=TS.EnergyBin[Epnt+1]; } if (Tpnt==0 || Epnt==0) { fprintf(stderr,"BIG ERROR WITH Tpnt: %d and Epnt: %d\n",Tpnt,Epnt); exit(1); } if (Tpnt==TS.nTime) { fprintf(stderr,"BIG ERROR WITH Tpnt and Epnt\n"); exit(1); *TV=0.0; Tspread=TS.Flux[Epnt-1][0]-TS.EInt[Epnt-1]; TRange=TS.TimeBin[0]; R-=TS.EInt[Epnt-1]; } else { *TV=TS.TimeBin[Tpnt-1]; TRange=TS.TimeBin[Tpnt]-TS.TimeBin[Tpnt-1]; Tspread=TS.Flux[Epnt-1][Tpnt]-TS.Flux[Epnt-1][Tpnt-1]; R-=TS.Flux[Epnt-1][Tpnt-1]; } // printf("R == %12.6e\n",R); R/=Tspread; // printf("R == %12.6e\n",R); *TV+=TRange*R; R1=TS.EInt[Epnt-1]+Espread*rand01(); iStart=Epnt>lowPoly ? Epnt-lowPoly : 0; // max(Epnt-halfPoly,0) iEnd=TS.nEnergy>Epnt+highPoly ? Epnt+highPoly : TS.nEnergy-1; // min(nEnergy-1,Epnt+highPoly *EV=polInterp(TS.EInt+iStart,TS.EnergyBin+iStart,1+iEnd-iStart,R1); // fprintf(stderr,"Energy == %d %d %12.6e %12.6e \n",iStart,iEnd,R1,*EV); // fprintf(stderr,"bins == %12.6e %12.6e %12.6e %12.6e \n",TS.EnergyBin[iStart],TS.EnergyBin[iEnd], // TS.EInt[Epnt],TS.EInt[Epnt-1]); if(*TV < TS.TimeBin[Tpnt-1] || *TV > TS.TimeBin[Tpnt]) { fprintf(stderr,"%d Tpnt %d Tval %g Epnt %d \n",TS.nTime,Tpnt,*TV,Epnt); fprintf(stderr,"TBoundary == %12.6e,%g , %12.6e \n\n",TS.TimeBin[Tpnt-1],*TV,TS.TimeBin[Tpnt]); } if(*EV < *lim1 || *EV > *lim2) { fprintf(stderr,"outside boundaries\n Epnt= %d, Tpnt= %d binlo %g|%g| binhi %g \n",Epnt,Tpnt,TS.EnergyBin[Epnt-1],*EV,TS.EnergyBin[Epnt]); fprintf(stderr,"TS == %g %g :: %d %d \n",TS.EInt[Epnt-1],TS.EInt[Epnt],iStart,iEnd); fprintf(stderr,"Points (%g) == ",R1); for(i=0;i #if defined(__THINK__) || defined(__MWERKS__) #include #define CONSOLE_LINES 36 /* number of lines to use for console */ #define CONSOLE_COLUMNS 90 /* number of columns to use for console */ #ifdef __MWERKS__ #include #endif #endif #define AppMalloc(ptr, n) (ptr) = malloc((n) * sizeof (*(ptr))) #define AppFree(ptr, n) free(ptr) #define SGCOREDEF__ #include "sginfo.h" #define NXSLIB_VERSION 1.5 /** @author Mirko Boin, Helmholtz-Zentrum Berlin fü Materialien und Energy GmbH, */ /*! Details: The nxs library for computing neutron scattering and absorption cross sections provides a number of C structs and functions to calculate wavelength-dependent cross section values for polycrystalline/powder-like materials. The definition of a material is represented by the composition of a unit cell (NXS_UnitCell). A unit cell is created from the specification of a space group and its unit cell parameters. The SgInfo routines from Ralf W. Grosse-Kunstleve is included here for such purposes. Monoatomic materials as well as multi-atomic compounds are created by adding NXS_AtomInfo atom information/properties. The library also provides a reading and saving routines to compose unit cells from nxs parameter files. Example: The below example shows howto quickly use the library routines to initialise a unit cell from a parameter file and calculate some cross sections. \code{.c} NXS_UnitCell uc; if( NXS_ERROR_OK == nxs_initFromParameterFile( "Al.nxs", &uc ) ) { double lambda=0.1; for( lambda=0.1; lambda<4.0; lambda+=0.1 ) printf("%f\n",nxs_Absorption(lambda, &uc ) ); } \endcode A more comprehensive example shows use of individual atom parameters for the construction of a unit cell and the initialization of hkl lattice reflections in order to prepare for cross section calculations. \code{.c} NXS_UnitCell uc; NXS_AtomInfo *atomInfoList; int numAtoms = nxs_readParameterFile( "Al.nxs", &uc, &atomInfoList); if( numAtoms > 0 ) { int i=0; nxs_initUnitCell(&uc); for( i=0; i \brief struct for symmetry equivalent Miller indices (hkl) This struct is used by struct NXS_HKL to hold symmetry equivalent hkl. \see NXS_HKL */ typedef struct NXS_EquivHKL { int h; /*!< Miller index */ int k; /*!< Miller index */ int l; /*!< Miller index */ } NXS_EquivHKL; /** \struct \brief struct for Miller indices (hkl) According to a given reflection this struct stores the hkl indices, its multiplicity, its lattice spacing, its structure factor and the symmetry equivalent hkl indices. */ typedef struct NXS_HKL { int h; /*!< Miller index */ int k; /*!< Miller index */ int l; /*!< Miller index */ unsigned int multiplicity; /*!< multiplicity of the hkl reflection */ double dhkl; /*!< hkl lattice spacing in Å*/ double FSquare; /*!< \f$|F|^2\f$ (structure factor) */ NXS_EquivHKL *equivHKL; /*!< holds the symmetry equivalent reflections including the current indices */ } NXS_HKL; /** \struct \brief struct for atom descrpition This struct stores the position of an atom, its average cross sections, mass and Debye temperature. */ typedef struct NXS_AtomInfo { char wyckoffLetter; /*!< Wyckoff letter */ unsigned int nAtoms; /*!< number of atoms = Wyckoff multiplicity */ unsigned int elementNumber; /*!< Element number from PSE */ char label[MAX_CHARS_ATOMLABEL]; /*!< Label (name) for the atom */ double x[192]; /*!< holds the x positions, the first entry is the Wyckoff position */ double y[192]; /*!< holds the y positions, the first entry is the Wyckoff position */ double z[192]; /*!< holds the z positions, the first entry is the Wyckoff position */ double sigmaAbsorption; /*!< in [\f$barn = 10^{-24} cm^2 at \ 2200 \frac{m}{s} = 1.798 \AA\f$] */ double sigmaCoherent; /*!< in [\f$barn = 10^{-24} cm^2\f$] */ double sigmaIncoherent; /*!< in [\f$barn = 10^{-24} cm^2\f$] */ double b_coherent; /*!< in [fm] */ double molarMass; /*!< Molar mass in [\f$u = 1.66 \times 10^{-27} kg\f$] */ double M_m; /*! M/m = molarMass*ATOMIC_MASS_U_kg/MASS_NEUTRON_kg / */ double debyeTemp; /*!< Debye temperature in [K] */ double phi_1; /*!< \f$\varphi_1\f$ */ double phi_3; /*!< \f$\varphi_3\f$ */ double B_iso; /*!< \f$B_{iso}\f$ the isotropic atomic displacement factor */ double sph; /*!< Single phonon part per atom info */ } NXS_AtomInfo; /** \struct \brief struct for unit cell description This struct stores space group symbol, the lattice parameters, the three sigma values, the atom mass the Debye temperature, some calculated values and the HKL and UnitCell struct as well as the SgInfo struct (see SgInfo documentation on http://cci.lbl.gov/sginfo/). */ typedef struct NXS_UnitCell { int crystalSystem; /*!< crysal system: XS_Tetragonal, XS_Hexagonal, XS_Cubic ... */ char spaceGroup[MAX_CHARS_SPACEGROUP]; /*!< space group number or denotation */ double a; /*!< lattice constant a */ double b; /*!< lattice constant b */ double c; /*!< lattice constant c */ double alpha; /*!< lattice constant \f$\alpha\f$ */ double beta; /*!< lattice constant \f$\beta\f$ */ double gamma; /*!< lattice constant \f$\gamma\f$ */ double mph_c2; /*!< constant for mph calculation from A.K. Freund (1983) Nucl. Instr. Meth. 213, 495-501, if not defined C2 = 4.27*exp( A/61.0 ) will be calculated */ double debyeTemp; /*!< Debye temperature in [K] */ double avgSigmaCoherent; /*!< in [\f$barn = 10^{-24} cm^2\f$] */ double avgSigmaIncoherent; /*!< in [\f$barn = 10^{-24} cm^2\f$] */ unsigned int nAtoms; /*!< total number of atoms inside the unit cell */ unsigned int nAtomInfo; /*!< number of unit cell atoms */ NXS_AtomInfo *atomInfoList; /*!< atom info \see AtomInfo */ T_SgInfo sgInfo; /*!< struct from SgInfo library needed for further calculations see SgInfo documentation on http://cci.lbl.gov/sginfo/ */ double temperature; /*!< sample environment temperature [K] */ double volume; /*!< unit cell volume */ double mass; /*!< unit cell mass [\f$\frac{g}{mol}\f$]*/ double density; /*!< unit cell density [\f$\frac{g}{cm^3}\f$]*/ unsigned int nHKL; /*!< number of hkl reflections after initUnitCell() */ unsigned int maxHKL_index; /*!< maximum hkl index */ NXS_HKL *hklList; /*!< \see NXS_HKL */ unsigned char __flag_mph_c2; /*!< flag to indicate if mph_c2 is set or should be calculated */ } NXS_UnitCell; NXS_UnitCell nxs_newUnitCell(); int nxs_initUnitCell( NXS_UnitCell *uc ); int nxs_addAtomInfo( NXS_UnitCell *uc, NXS_AtomInfo ai ); int nxs_initHKL( NXS_UnitCell *uc ); double nxs_calcDhkl( int h, int k, int l, NXS_UnitCell *uc ); double nxs_calcFSquare( NXS_HKL *hklReflex, NXS_UnitCell *uc ); /*****************************************************************************/ /************************** CROSS SECTION FUNCTIONS **************************/ double nxs_Absorption ( double lambda, NXS_UnitCell* uc ); double nxs_CoherentElastic ( double lambda, NXS_UnitCell* uc ); double nxs_CoherentInelastic ( double lambda, NXS_UnitCell* uc ); double nxs_TotalInelastic ( double lambda, NXS_UnitCell* uc ); double nxs_TotalInelastic_BINDER ( double lambda, NXS_UnitCell* uc ); double nxs_TotalInelastic_COMBINED( double lambda, NXS_UnitCell* uc ); double nxs_SinglePhonon ( double lambda, NXS_UnitCell* uc ); double nxs_MultiPhonon ( double lambda, NXS_UnitCell* uc ); double nxs_MultiPhonon_CASSELS ( double lambda, NXS_UnitCell* uc ); double nxs_MultiPhonon_FREUND ( double lambda, NXS_UnitCell* uc ); double nxs_MultiPhonon_COMBINED ( double lambda, NXS_UnitCell* uc ); double nxs_IncoherentElastic ( double lambda, NXS_UnitCell* uc ); double nxs_IncoherentInelastic ( double lambda, NXS_UnitCell* uc ); /*****************************************************************************/ /******************************* TEXTURE STUFF *******************************/ /** \struct \brief struct for texture descrpition using March-Dollase approach */ typedef struct NXS_Texture { int a; int b; int c; double r; double f; double **sin_beta; double **cos_beta; double *P_alpha_H; } NXS_Texture; /** \struct \brief struct for March-Dollase correction calculation */ typedef struct NXS_MarchDollase { unsigned int M; unsigned int N; unsigned int nOrientations; double *sin_phi; double *cos_phi; NXS_Texture *texture; NXS_UnitCell *unitcell; } NXS_MarchDollase; NXS_MarchDollase nxs_initMarchDollase( NXS_UnitCell* uc ); void nxs_addTexture( NXS_MarchDollase* md, NXS_Texture texture ); double nxs_CoherentElasticTexture( double lambda, NXS_MarchDollase* md ); /*****************************************************************************/ /************************** PARAMETER FILE ROUTINES **************************/ int nxs_readParameterFile( const char* fileName, NXS_UnitCell *uc , NXS_AtomInfo *atomInfoList[] ); int nxs_saveParameterFile( const char* fileName, NXS_UnitCell *uc ); int nxs_initFromParameterFile( const char* fileName, NXS_UnitCell *uc ); /*****************************************************************************/ #endif #ifdef __cplusplus } #endif /******************************************************************************* * * McStas, neutron ray-tracing package * Copyright 1997-2002, All rights reserved * Risoe National Laboratory, Roskilde, Denmark * Institut Laue Langevin, Grenoble, France * * Library: share/read_table-lib.h * * %Identification * Written by: EF * Date: Aug 28, 2002 * Origin: ILL * Release: McStas 1.6 * Version: $Revision$ * * This file is to be imported by components that may read data from table files * It handles some shared functions. * * This library may be used directly as an external library. It has no dependency * * Usage: within SHARE * %include "read_table-lib" * *******************************************************************************/ #ifndef READ_TABLE_LIB_H #define READ_TABLE_LIB_H "$Revision$" #define READ_TABLE_STEPTOL 0.04 /* tolerancy for constant step approx */ #ifndef MC_PATHSEP_C #ifdef WIN32 #define MC_PATHSEP_C '\\' #define MC_PATHSEP_S "\\" #else /* !WIN32 */ #ifdef MAC #define MC_PATHSEP_C ':' #define MC_PATHSEP_S ":" #else /* !MAC */ #define MC_PATHSEP_C '/' #define MC_PATHSEP_S "/" #endif /* !MAC */ #endif /* !WIN32 */ #endif /* !MC_PATHSEP_C */ #ifndef MCSTAS #ifdef WIN32 #define MCSTAS "C:\\mcstas\\lib" #else /* !WIN32 */ #ifdef MAC #define MCSTAS ":mcstas:lib" /* ToDo: What to put here? */ #else /* !MAC */ #define MCSTAS "/usr/local/lib/mcstas" #endif /* !MAC */ #endif /* !WIN32 */ #endif /* !MCSTAS */ #include #include #include typedef struct struct_table { char filename[1024]; long filesize; char *header; /* text header, e.g. comments */ double *data; /* vector { x[0], y[0], ... x[n-1], y[n-1]... } */ double min_x; /* min value of first column */ double max_x; /* max value of first column */ double step_x; /* minimal step value of first column */ long rows; /* number of rows in matrix block */ long columns; /* number of columns in matrix block */ long begin; /* start fseek index of block */ long end; /* stop fseek index of block */ long block_number; /* block index. 0 is catenation of all */ long array_length; /* number of elements in the t_Table array */ char monotonic; /* true when 1st column/vector data is monotonic */ char constantstep; /* true when 1st column/vector data has constant step */ char method[32]; /* interpolation method: nearest, linear */ } t_Table; typedef struct t_Read_table_file_item { int ref_count; t_Table *table_ref; } t_Read_table_file_item; typedef enum enum_Read_table_file_actions {STORE,FIND,GC} t_Read_table_file_actions; /* read_table-lib function prototypes */ /* ========================================================================= */ /* 'public' functions */ long Table_Read (t_Table *Table, char *File, long block_number); long Table_Read_Offset (t_Table *Table, char *File, long block_number, long *offset, long max_lines); long Table_Read_Offset_Binary(t_Table *Table, char *File, char *Type, long *Offset, long Rows, long Columns); long Table_Rebin(t_Table *Table); /* rebin table with regular 1st column and interpolate all columns 2:end */ long Table_Info (t_Table Table); double Table_Index(t_Table Table, long i, long j); /* get indexed value */ double Table_Value(t_Table Table, double X, long j); /* search X in 1st column and return interpolated value in j-column */ t_Table *Table_Read_Array(char *File, long *blocks); void Table_Free_Array(t_Table *Table); long Table_Info_Array(t_Table *Table); int Table_SetElement(t_Table *Table, long i, long j, double value); long Table_Init(t_Table *Table, long rows, long columns); /* create a Table */ double Table_Value2d(t_Table Table, double X, double Y); /* same as Table_Index with non-integer indices and 2d interpolation */ MCDETECTOR Table_Write(t_Table Table, char*file, char*xl, char*yl, double x1, double x2, double y1, double y2); /* write Table to disk */ void * Table_File_List_Handler(t_Read_table_file_actions action, void *item, void *item_modifier); t_Table *Table_File_List_find(char *name, int block, int offset); int Table_File_List_gc(t_Table *tab); void *Table_File_List_store(t_Table *tab); #define Table_ParseHeader(header, ...) \ Table_ParseHeader_backend(header,__VA_ARGS__,NULL); char **Table_ParseHeader_backend(char *header, ...); /* private functions */ void Table_Free(t_Table *Table); long Table_Read_Handle(t_Table *Table, FILE *fid, long block_number, long max_lines, char *name); static void Table_Stat(t_Table *Table); double Table_Interp1d(double x, double x1, double y1, double x2, double y2); double Table_Interp1d_nearest(double x, double x1, double y1, double x2, double y2); double Table_Interp2d(double x, double y, double x1, double y1, double x2, double y2, double z11, double z12, double z21, double z22); #endif /* end of read_table-lib.h */ /******************************************************************************* * * McStas, neutron ray-tracing package * Copyright (C) 1997-2009, All rights reserved * Risoe National Laboratory, Roskilde, Denmark * Institut Laue Langevin, Grenoble, France * * Library: share/read_table-lib.c * * %Identification * Written by: EF * Date: Aug 28, 2002 * Origin: ILL * Release: McStas CVS_090504 * Version: $Revision: 5052 $ * * This file is to be imported by components that may read data from table files * It handles some shared functions. Embedded within instrument in runtime mode. * * Usage: within SHARE * %include "read_table-lib" * *******************************************************************************/ #ifndef READ_TABLE_LIB_H #include "read_table-lib.h" #endif /******************************************************************************* * void *Table_File_List_Handler(action, item, item_modifier) * ACTION: handle file entries in the read_table-lib file list. If a file is read - it is supposed to be * stored in a list such that we can avoid reading the same file many times. * input action: FIND, STORE, GC. check if file exists in the list, store an item in the list, or check if it can be garbage collected. * input item: depends on the action. * FIND) item is a filename, and item_modifier is the block number * STORE) item is the Table to store - item_modifier is ignored * GC) item is the Table to check. If it has a ref_count >1 then this is simply decremented. * return depends on the action * FIND) return a reference to a table+ref_count item if found - NULL otherwise. I.e. NULL means the file has not been read before and must be read again. * STORE) return NULL always * GC) return NULL if no garbage collection is needed, return an adress to the t_Table which should be garbage collected. 0x1 is returned if * the item is not found in the list *******************************************************************************/ void * Table_File_List_Handler(t_Read_table_file_actions action, void *item, void *item_modifier){ /* logic here is Read_Table should include a call to FIND. If found the return value shoud just be used as * if the table had been read. If not found then read the table and STORE. * Table_Free should include a call to GC. If this returns non-NULL then we shoudl proceed with freeing the memory * associated with the table item - otherwise do nothing since there are more references that may need it.*/ static t_Read_table_file_item read_table_file_list[1024]; static int read_table_file_count=0; t_Read_table_file_item *tr; switch(action){ case FIND: /*interpret data item as a filename, if it is found return a pointer to the table and increment refcount. * if not found return the item itself*/ tr=read_table_file_list; while ( tr->table_ref!=NULL ){ int i=*((int*) item_modifier); int j=*( ((int*) item_modifier)+1); if ( !strcmp(tr->table_ref->filename,(char *) item) && tr->table_ref->block_number==i && tr->table_ref->begin==j ){ tr->ref_count++; return (void *) tr; } tr++; } return NULL; case STORE: /*find an available slot and store references to table there*/ tr=&(read_table_file_list[read_table_file_count++]); tr->table_ref=(t_Table *)calloc(1,sizeof(t_Table)); /*copy the contents of the table handle*/ *(tr->table_ref)= *((t_Table *) item); tr->ref_count++; return NULL; case GC: /* Should this item be garbage collected (freed) - if so scratch the entry and return the address of the item - * else decrement ref_count and return NULL. * A non-NULL return expects the item to actually be freed afterwards.*/ tr=read_table_file_list; while ( tr->table_ref!=NULL ){ if ( tr->table_ref->data ==((t_Table *)item)->data && tr->table_ref->block_number == ((t_Table *)item)->block_number){ /*matching item found*/ if (tr->ref_count>1){ /*the item is found - no garbage collection needed*/ tr->ref_count--; return NULL; }else{ /* The item is found - move remaining list items up one slot, * and return the table for garbage collection by caller*/ while (tr->table_ref!=NULL){ *tr=*(tr+1); tr++; } read_table_file_count--; return (t_Table *) item; } } tr++; } return (void *)0x1 ;/*item not found*/ } } /* Access functions to the handler*/ /******************************************** * t_Table *Table_File_List_find(char *name, int block, int offset) * input name: filename to search for in the file list * input block: data block in the file as each file may contain more than 1 data block. * return a ref. to a table if it is found (you may use this pointer and skip reading the file), NULL otherwise (i.e. go ahead and read the file) *********************************************/ t_Table *Table_File_List_find(char *name, int block, int offset){ int vars[2]={block,offset}; t_Read_table_file_item *item = Table_File_List_Handler(FIND,name, vars); if (item == NULL){ return NULL; }else{ return item->table_ref; } } /******************************************** * int Table_File_List_gc(t_Table *tab) * input tab: the table to check for references. * return 0: no garbage collection needed * 1: Table's data and header (at least) should be freed. *********************************************/ int Table_File_List_gc(t_Table *tab){ void *rval=Table_File_List_Handler(GC,tab,0); if (rval==NULL) return 0; else return 1; } /***************************************************************************** * void *Table_File_List_store(t_Table *tab) * input tab: pointer to table to store. * return None. *******************************************************************************/ void *Table_File_List_store(t_Table *tab){ Table_File_List_Handler(STORE,tab,0); } /******************************************************************************* * FILE *Open_File(char *name, char *Mode, char *path) * ACTION: search for a file and open it. Optionally return the opened path. * input name: file name from which table should be extracted * mode: "r", "w", "a" or any valid fopen mode * path: NULL or a pointer to at least 1024 allocated chars * return initialized file handle or NULL in case of error *******************************************************************************/ FILE *Open_File(char *File, const char *Mode, char *Path) { char path[1024]; FILE *hfile = NULL; if (!File || File[0]=='\0') return(NULL); if (!strcmp(File,"NULL") || !strcmp(File,"0")) return(NULL); /* search in current or full path */ strncpy(path, File, 1024); hfile = fopen(path, Mode); if(!hfile) { char dir[1024]; if (!hfile && mcinstrument_source && strlen(mcinstrument_source)) /* search in instrument source location */ { char *path_pos = NULL; /* extract path: searches for last file separator */ path_pos = strrchr(mcinstrument_source, MC_PATHSEP_C); /* last PATHSEP */ if (path_pos) { long path_length = path_pos +1 - mcinstrument_source; /* from start to path+sep */ if (path_length) { strncpy(dir, mcinstrument_source, path_length); dir[path_length] = '\0'; snprintf(path, 1024, "%s%c%s", dir, MC_PATHSEP_C, File); hfile = fopen(path, Mode); } } } if (!hfile && mcinstrument_exe && strlen(mcinstrument_exe)) /* search in PWD instrument executable location */ { char *path_pos = NULL; /* extract path: searches for last file separator */ path_pos = strrchr(mcinstrument_exe, MC_PATHSEP_C); /* last PATHSEP */ if (path_pos) { long path_length = path_pos +1 - mcinstrument_exe; /* from start to path+sep */ if (path_length) { strncpy(dir, mcinstrument_exe, path_length); dir[path_length] = '\0'; snprintf(path, 1024, "%s%c%s", dir, MC_PATHSEP_C, File); hfile = fopen(path, Mode); } } } if (!hfile) /* search in HOME or . */ { strcpy(dir, getenv("HOME") ? getenv("HOME") : "."); snprintf(path, 1024, "%s%c%s", dir, MC_PATHSEP_C, File); hfile = fopen(path, Mode); } if (!hfile) /* search in MCSTAS/data */ { strcpy(dir, getenv(FLAVOR_UPPER) ? getenv(FLAVOR_UPPER) : MCSTAS); snprintf(path, 1024, "%s%c%s%c%s", dir, MC_PATHSEP_C, "data", MC_PATHSEP_C, File); hfile = fopen(path, Mode); } if (!hfile) /* search in MVCSTAS/contrib */ { strcpy(dir, getenv(FLAVOR_UPPER) ? getenv(FLAVOR_UPPER) : MCSTAS); snprintf(path, 1024, "%s%c%s%c%s", dir, MC_PATHSEP_C, "contrib", MC_PATHSEP_C, File); hfile = fopen(path, Mode); } if(!hfile) { fprintf(stderr, "Error: Could not open input file '%s' (Open_File)\n", File); return (NULL); } } if (Path) strncpy(Path, path, 1024); return(hfile); } /* end Open_File */ /******************************************************************************* * long Read_Table(t_Table *Table, char *name, int block_number) * ACTION: read a single Table from a text file * input Table: pointer to a t_Table structure * name: file name from which table should be extracted * block_number: if the file does contain more than one * data block, then indicates which one to get (from index 1) * a 0 value means append/catenate all * return initialized single Table t_Table structure containing data, header, ... * number of read elements (-1: error, 0:header only) * The routine stores any line starting with '#', '%' and ';' into the header * File is opened, read and closed * Other lines are interpreted as numerical data, and stored. * Data block should be a rectangular matrix or vector. * Data block may be rebinned with Table_Rebin (also sort in ascending order) *******************************************************************************/ long Table_Read(t_Table *Table, char *File, long block_number) { /* reads all or a single data block from 'file' and returns a Table structure */ return(Table_Read_Offset(Table, File, block_number, NULL, 0)); } /* end Table_Read */ /******************************************************************************* * long Table_Read_Offset(t_Table *Table, char *name, int block_number, long *offset * long max_rows) * ACTION: read a single Table from a text file, starting at offset * Same as Table_Read(..) except: * input offset: pointer to an offset (*offset should be 0 at start) * max_rows: max number of data rows to read from file (0 means all) * return initialized single Table t_Table structure containing data, header, ... * number of read elements (-1: error, 0:header only) * updated *offset position (where end of reading occured) *******************************************************************************/ long Table_Read_Offset(t_Table *Table, char *File, long block_number, long *offset, long max_rows) { /* reads all/a data block in 'file' and returns a Table structure */ FILE *hfile; long nelements=0; long begin=0; long filesize=0; char name[1024]; char path[1024]; struct stat stfile; /*Need to be able to store the pointer*/ if (!Table) return(-1); //if (offset && *offset) snprintf(name, 1024, "%s@%li", File, *offset); //else strncpy(name, File, 1024); if(offset && *offset){ begin=*offset; } /* Check if the table has already been read from file. * If so just reuse the table, if not (this is flagged by returning NULL * set up a new table and read the data into it */ t_Table *tab_p= Table_File_List_find(name,block_number,begin); if ( tab_p!=NULL ){ /*table was found in the Table_File_List*/ printf("Reusing input file '%s' (Table_Read_Offset)\n", name); *Table=*tab_p; return Table->rows*Table->columns; } /* open the file */ hfile = Open_File(File, "r", path); if (!hfile) return(-1); else { MPI_MASTER( printf("Opening input file '%s' (Table_Read_Offset)\n", path); ); } /* read file state */ stat(path,&stfile); filesize = stfile.st_size; if (offset && *offset) fseek(hfile, *offset, SEEK_SET); begin = ftell(hfile); Table_Init(Table, 0, 0); /* read file content and set the Table */ nelements = Table_Read_Handle(Table, hfile, block_number, max_rows, name); Table->begin = begin; Table->end = ftell(hfile); Table->filesize = (filesize>0 ? filesize : 0); Table_Stat(Table); Table_File_List_store(Table); if (offset) *offset=Table->end; fclose(hfile); return(nelements); } /* end Table_Read_Offset */ /******************************************************************************* * long Table_Read_Offset_Binary(t_Table *Table, char *File, char *type, * long *offset, long rows, long columns) * ACTION: read a single Table from a binary file, starting at offset * Same as Table_Read_Offset(..) except that it handles binary files. * input type: may be "float"/NULL or "double" * offset: pointer to an offset (*offset should be 0 at start) * rows : number of rows (0 means read all) * columns: number of columns * return initialized single Table t_Table structure containing data, header, ... * number of read elements (-1: error, 0:header only) * updated *offset position (where end of reading occured) *******************************************************************************/ long Table_Read_Offset_Binary(t_Table *Table, char *File, char *type, long *offset, long rows, long columns) { /* reads all/a data block in binary 'file' and returns a Table structure */ long nelements, sizeofelement; long filesize; FILE *hfile; char path[1024]; struct stat stfile; double *data; long i; long begin; if (!Table) return(-1); Table_Init(Table, 0, 0); /* open the file */ hfile = Open_File(File, "r", path); if (!hfile) return(-1); else { MPI_MASTER( printf("Opening input file '%s' (Table_Read, Binary)\n", path); ); } /* read file state */ stat(File,&stfile); filesize = stfile.st_size; Table->filesize=filesize; /* read file content */ if (type && !strcmp(type,"double")) sizeofelement = sizeof(double); else sizeofelement = sizeof(float); if (offset && *offset) fseek(hfile, *offset, SEEK_SET); begin = ftell(hfile); if (rows && filesize > sizeofelement*columns*rows) nelements = columns*rows; else nelements = (long)(filesize/sizeofelement); if (!nelements || filesize <= *offset) return(0); data = (double*)malloc(nelements*sizeofelement); if (!data) { fprintf(stderr,"Error: allocating %ld elements for %s file '%s'. Too big (Table_Read_Offset_Binary).\n", nelements, type, File); exit(-1); } nelements = fread(data, sizeofelement, nelements, hfile); if (!data || !nelements) { fprintf(stderr,"Error: reading %ld elements from %s file '%s' (Table_Read_Offset_Binary)\n", nelements, type, File); exit(-1); } Table->begin = begin; Table->end = ftell(hfile); if (offset) *offset=Table->end; fclose(hfile); data = (double*)realloc(data, (double)nelements*sizeofelement); /* copy file data into Table */ if (type && !strcmp(type,"double")) Table->data = data; else { float *s; double *dataf; s = (float*)data; dataf = (double*)malloc(sizeof(double)*nelements); for (i=0; idata = dataf; } strncpy(Table->filename, File, 1024); Table->rows = nelements/columns; Table->columns = columns; Table->array_length = 1; Table->block_number = 1; Table_Stat(Table); return(nelements); } /* end Table_Read_Offset_Binary */ /******************************************************************************* * long Table_Read_Handle(t_Table *Table, FILE *fid, int block_number, long max_rows, char *name) * ACTION: read a single Table from a text file handle (private) * input Table:pointer to a t_Table structure * fid: pointer to FILE handle * block_number: if the file does contain more than one * data block, then indicates which one to get (from index 1) * a 0 value means append/catenate all * max_rows: if non 0, only reads that number of lines * return initialized single Table t_Table structure containing data, header, ... * modified Table t_Table structure containing data, header, ... * number of read elements (-1: error, 0:header only) * The routine stores any line starting with '#', '%' and ';' into the header * Other lines are interpreted as numerical data, and stored. * Data block should be a rectangular matrix or vector. * Data block may be rebined with Table_Rebin (also sort in ascending order) *******************************************************************************/ long Table_Read_Handle(t_Table *Table, FILE *hfile, long block_number, long max_rows, char *name) { /* reads all/a data block from 'file' handle and returns a Table structure */ double *Data; char *Header = NULL; long malloc_size = CHAR_BUF_LENGTH; long malloc_size_h = 4096; long Rows = 0, Columns = 0; long count_in_array = 0; long count_in_header = 0; long block_Current_index = 0; char flag_End_row_loop = 0; if (!Table) return(-1); Table_Init(Table, 0, 0); if (name && name[0]!='\0') strncpy(Table->filename, name, 1024); if(!hfile) { fprintf(stderr, "Error: File handle is NULL (Table_Read_Handle).\n"); return (-1); } Header = (char*) calloc(malloc_size_h, sizeof(char)); Data = (double*)calloc(malloc_size, sizeof(double)); if ((Header == NULL) || (Data == NULL)) { fprintf(stderr, "Error: Could not allocate Table and Header (Table_Read_Handle).\n"); return (-1); } int flag_In_array = 0; do { /* while (!flag_End_row_loop) */ char line[1024*CHAR_BUF_LENGTH]; long back_pos=0; /* ftell start of line */ back_pos = ftell(hfile); if (fgets(line, 1024*CHAR_BUF_LENGTH, hfile) != NULL) { /* analyse line */ /* first skip blank and tabulation characters */ int i = strspn(line, " \t"); /* handle comments: stored in header */ if (NULL != strchr("#%;/", line[i])) { /* line is a comment */ count_in_header += strlen(line); if (count_in_header >= malloc_size_h) { /* if succeed and in array : add (and realloc if necessary) */ malloc_size_h = count_in_header+4096; Header = (char*)realloc(Header, malloc_size_h*sizeof(char)); } strncat(Header, line, 4096); flag_In_array=0; /* exit line and file if passed desired block */ if (block_number > 0 && block_number == block_Current_index) { flag_End_row_loop = 1; } /* Continue with next line */ continue; } /* get the number of columns splitting line with strtok */ char *lexeme; char flag_End_Line = 0; long block_Num_Columns = 0; const char seps[] = " ,;\t\n\r"; lexeme = strtok(line, seps); while (!flag_End_Line) { if ((lexeme != NULL) && (lexeme[0] != '\0')) { /* reading line: the token is not empty */ double X; int count=1; /* test if we have 'NaN','Inf' */ if (!strncasecmp(lexeme,"NaN",3)) X = 0; else if (!strncasecmp(lexeme,"Inf",3) || !strncasecmp(lexeme,"+Inf",4)) X = FLT_MAX; else if (!strncasecmp(lexeme,"-Inf",4)) X = -FLT_MAX; else count = sscanf(lexeme,"%lg",&X); if (count == 1) { /* reading line: the token is a number in the line */ if (!flag_In_array) { /* reading num: not already in a block: starts a new data block */ block_Current_index++; flag_In_array = 1; block_Num_Columns= 0; if (block_number > 0) { /* initialise a new data block */ Rows = 0; count_in_array = 0; } /* else append */ } /* reading num: all blocks or selected block */ if (flag_In_array && (block_number == 0 || block_number == block_Current_index)) { /* starting block: already the desired number of rows ? */ if (block_Num_Columns == 0 && max_rows > 0 && Rows >= max_rows) { flag_End_Line = 1; flag_End_row_loop = 1; flag_In_array = 0; /* reposition to begining of line (ignore line) */ fseek(hfile, back_pos, SEEK_SET); } else { /* store into data array */ if (count_in_array >= malloc_size) { /* realloc data buffer if necessary */ malloc_size = count_in_array+CHAR_BUF_LENGTH; Data = (double*) realloc(Data, malloc_size*sizeof(double)); if (Data == NULL) { fprintf(stderr, "Error: Can not re-allocate memory %li (Table_Read_Handle).\n", malloc_size*sizeof(double)); return (-1); } } if (0 == block_Num_Columns) Rows++; Data[count_in_array] = X; count_in_array++; block_Num_Columns++; } } /* reading num: end if flag_In_array */ } /* end reading num: end if sscanf lexeme -> numerical */ else { /* reading line: the token is not numerical in that line. end block */ if (block_Current_index == block_number) { flag_End_Line = 1; flag_End_row_loop = 1; } else { flag_In_array = 0; flag_End_Line = 1; } } } else { /* no more tokens in line */ flag_End_Line = 1; if (block_Num_Columns > 0) Columns = block_Num_Columns; } // parse next token lexeme = strtok(NULL, seps); } /* while (!flag_End_Line) */ } /* end: if fgets */ else flag_End_row_loop = 1; /* else fgets : end of file */ } while (!flag_End_row_loop); /* end while flag_End_row_loop */ Table->block_number = block_number; Table->array_length = 1; // shrink header to actual size (plus terminating 0-byte) if (count_in_header) { Header = (char*)realloc(Header, count_in_header*sizeof(char) + 1); } Table->header = Header; if (count_in_array*Rows*Columns == 0) { Table->rows = 0; Table->columns = 0; free(Data); return (0); } if (Rows * Columns != count_in_array) { fprintf(stderr, "Warning: Read_Table :%s %s Data has %li values that should be %li x %li\n", (Table->filename ? Table->filename : ""), (!block_number ? " catenated" : ""), count_in_array, Rows, Columns); Columns = count_in_array; Rows = 1; } Data = (double*)realloc(Data, count_in_array*sizeof(double)); Table->data = Data; Table->rows = Rows; Table->columns = Columns; return (count_in_array); } /* end Table_Read_Handle */ /******************************************************************************* * long Table_Rebin(t_Table *Table) * ACTION: rebin a single Table, sorting 1st column in ascending order * input Table: single table containing data. * The data block is reallocated in this process * return updated Table with increasing, evenly spaced first column (index 0) * number of data elements (-1: error, 0:empty data) *******************************************************************************/ long Table_Rebin(t_Table *Table) { double new_step=0; long i; /* performs linear interpolation on X axis (0-th column) */ if (!Table) return(-1); if (!Table->data || Table->rows*Table->columns == 0 || !Table->step_x) return(0); Table_Stat(Table); /* recompute statitstics and minimal step */ new_step = Table->step_x; /* minimal step in 1st column */ if (!(Table->constantstep)) /* not already evenly spaced */ { long Length_Table; double *New_Table; Length_Table = ceil(fabs(Table->max_x - Table->min_x)/new_step)+1; New_Table = (double*)malloc(Length_Table*Table->columns*sizeof(double)); for (i=0; i < Length_Table; i++) { long j; double X; X = Table->min_x + i*new_step; New_Table[i*Table->columns] = X; for (j=1; j < Table->columns; j++) New_Table[i*Table->columns+j] = Table_Value(*Table, X, j); } /* end for i */ Table->rows = Length_Table; Table->step_x = new_step; Table->max_x = Table->min_x + (Length_Table-1)*new_step; /*max might not be the same anymore * Use Length_Table -1 since the first and laset rows are the limits of the defined interval.*/ free(Table->data); Table->data = New_Table; Table->constantstep=1; } /* end else (!constantstep) */ return (Table->rows*Table->columns); } /* end Table_Rebin */ /******************************************************************************* * double Table_Index(t_Table Table, long i, long j) * ACTION: read an element [i,j] of a single Table * input Table: table containing data * i : index of row (0:Rows-1) * j : index of column (0:Columns-1) * return Value = data[i][j] * Returns Value from the i-th row, j-th column of Table * Tests are performed on indexes i,j to avoid errors *******************************************************************************/ #ifndef MIN #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MAX #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif double Table_Index(t_Table Table, long i, long j) { long AbsIndex; if (Table.rows == 1 || Table.columns == 1) { /* vector */ j = MIN(MAX(0, i+j), Table.columns*Table.rows - 1); i = 0; } else { /* matrix */ i = MIN(MAX(0, i), Table.rows - 1); j = MIN(MAX(0, j), Table.columns - 1); } /* handle vectors specifically */ AbsIndex = i*(Table.columns)+j; if (Table.data != NULL) return (Table.data[AbsIndex]); else return 0; } /* end Table_Index */ /******************************************************************************* * void Table_SetElement(t_Table *Table, long i, long j, double value) * ACTION: set an element [i,j] of a single Table * input Table: table containing data * i : index of row (0:Rows-1) * j : index of column (0:Columns-1) * value = data[i][j] * Returns 0 in case of error * Tests are performed on indexes i,j to avoid errors *******************************************************************************/ int Table_SetElement(t_Table *Table, long i, long j, double value) { long AbsIndex; if (Table->rows == 1 || Table->columns == 1) { /* vector */ j = MIN(MAX(0, i+j), Table->columns*Table->rows - 1); i=0; } else { /* matrix */ i = MIN(MAX(0, i), Table->rows - 1); j = MIN(MAX(0, j), Table->columns - 1); } AbsIndex = i*(Table->columns)+j; if (Table->data != NULL) { Table->data[AbsIndex] = value; return 1; } return 0; } /* end Table_SetElement */ /******************************************************************************* * double Table_Value(t_Table Table, double X, long j) * ACTION: read column [j] of a single Table at row which 1st column is X * input Table: table containing data. * X : data value in the first column (index 0) * j : index of column from which is extracted the Value (0:Columns-1) * return Value = data[index for X][j] with linear interpolation * Returns Value from the j-th column of Table corresponding to the * X value for the 1st column (index 0) * Tests are performed (within Table_Index) on indexes i,j to avoid errors * NOTE: data should rather be monotonic, and evenly sampled. *******************************************************************************/ double Table_Value(t_Table Table, double X, long j) { long Index = -1; double X1=0, Y1=0, X2=0, Y2=0; double ret=0; if (X > Table.max_x) return Table_Index(Table,Table.rows-1 ,j); if (X < Table.min_x) return Table_Index(Table,0 ,j); // Use constant-time lookup when possible if(Table.constantstep) { Index = (long)floor( (X - Table.min_x) / (Table.max_x - Table.min_x) * (Table.rows-1)); X1 = Table_Index(Table,Index ,0); X2 = Table_Index(Table,Index+1,0); } // Use binary search on large, monotonic tables else if(Table.monotonic && Table.rows > 100) { long left = Table.min_x; long right = Table.max_x; while (!((X1 <= X) && (X < X2)) && (right - left > 1)) { Index = (left + right) / 2; X1 = Table_Index(Table, Index-1, 0); X2 = Table_Index(Table, Index, 0); if (X < X1) { right = Index; } else { left = Index; } } } // Fall back to linear search, if no-one else has set X1, X2 correctly if (!((X1 <= X) && (X < X2))) { /* look for index surrounding X in the table -> Index */ for (Index=1; Index < Table.rows-1; Index++) { X1 = Table_Index(Table, Index-1,0); X2 = Table_Index(Table, Index ,0); if ((X1 <= X) && (X < X2)) break; } /* end for Index */ } Y1 = Table_Index(Table,Index-1,j); Y2 = Table_Index(Table,Index ,j); if (!strcmp(Table.method,"linear")) { ret = Table_Interp1d(X, X1,Y1, X2,Y2); } else if (!strcmp(Table.method,"nearest")) { ret = Table_Interp1d_nearest(X, X1,Y1, X2,Y2); } return ret; } /* end Table_Value */ /******************************************************************************* * double Table_Value2d(t_Table Table, double X, double Y) * ACTION: read element [X,Y] of a matrix Table * input Table: table containing data. * X : row index, may be non integer * Y : column index, may be non integer * return Value = data[index X][index Y] with bi-linear interpolation * Returns Value for the indices [X,Y] * Tests are performed (within Table_Index) on indexes i,j to avoid errors * NOTE: data should rather be monotonic, and evenly sampled. *******************************************************************************/ double Table_Value2d(t_Table Table, double X, double Y) { long x1,x2,y1,y2; double z11,z12,z21,z22; double ret=0; x1 = (long)floor(X); y1 = (long)floor(Y); if (x1 > Table.rows-1 || x1 < 0) { x2 = x1; } else { x2 = x1 + 1; } if (y1 > Table.columns-1 || y1 < 0) { y2 = y1; } else { y2 = y1 + 1; } z11 = Table_Index(Table, x1, y1); if (y2 != y1) z12=Table_Index(Table, x1, y2); else z12 = z11; if (x2 != x1) z21=Table_Index(Table, x2, y1); else z21 = z11; if (y2 != y1) z22=Table_Index(Table, x2, y2); else z22 = z21; if (!strcmp(Table.method,"linear")) ret = Table_Interp2d(X,Y, x1,y1,x2,y2, z11,z12,z21,z22); else { if (fabs(X-x1) < fabs(X-x2)) { if (fabs(Y-y1) < fabs(Y-y2)) ret = z11; else ret = z12; } else { if (fabs(Y-y1) < fabs(Y-y2)) ret = z21; else ret = z22; } } return ret; } /* end Table_Value2d */ /******************************************************************************* * void Table_Free(t_Table *Table) * ACTION: free a single Table * return: empty Table *******************************************************************************/ void Table_Free(t_Table *Table) { if( !Table_File_List_gc(Table) ){ return; } if (!Table) return; if (Table->data != NULL) free(Table->data); if (Table->header != NULL) free(Table->header); Table->data = NULL; Table->header = NULL; } /* end Table_Free */ /****************************************************************************** * void Table_Info(t_Table Table) * ACTION: print informations about a single Table *******************************************************************************/ long Table_Info(t_Table Table) { char buffer[256]; long ret=0; if (!Table.block_number) strcpy(buffer, "catenated"); else sprintf(buffer, "block %li", Table.block_number); printf("Table from file '%s' (%s)", Table.filename ? Table.filename : "", buffer); if ((Table.data != NULL) && (Table.rows*Table.columns)) { printf(" is %li x %li ", Table.rows, Table.columns); if (Table.rows*Table.columns > 1) printf("(x=%g:%g)", Table.min_x, Table.max_x); else printf("(x=%g) ", Table.min_x); ret = Table.rows*Table.columns; if (Table.monotonic) printf(", monotonic"); if (Table.constantstep) printf(", constant step"); printf(". interpolation: %s\n", Table.method); } else printf(" is empty.\n"); if (Table.header && strlen(Table.header)) { char *header; int i; header = malloc(80); if (!header) return(ret); for (i=0; i<80; header[i++]=0); strncpy(header, Table.header, 75); if (strlen(Table.header) > 75) { strcat( header, " ..."); } for (i=0; iheader = NULL; Table->filename[0]= '\0'; Table->filesize= 0; Table->min_x = 0; Table->max_x = 0; Table->step_x = 0; Table->block_number = 0; Table->array_length = 0; Table->monotonic = 0; Table->constantstep = 0; Table->begin = 0; Table->end = 0; strcpy(Table->method,"linear"); if (rows*columns >= 1) { data = (double*)malloc(rows*columns*sizeof(double)); if (data) for (i=0; i < rows*columns; data[i++]=0); else { fprintf(stderr,"Error: allocating %ld double elements." "Too big (Table_Init).\n", rows*columns); rows = columns = 0; } } Table->rows = (rows >= 1 ? rows : 0); Table->columns = (columns >= 1 ? columns : 0); Table->data = data; return(Table->rows*Table->columns); } /* end Table_Init */ /****************************************************************************** * long Table_Write(t_Table Table, char *file, x1,x2, y1,y2) * ACTION: write a Table to disk (ascii). * when x1=x2=0 or y1=y2=0, the table default limits are used. * return: 0=all is fine, non-0: error *******************************************************************************/ MCDETECTOR Table_Write(t_Table Table, char *file, char *xl, char *yl, double x1, double x2, double y1, double y2) { long i =0; MCDETECTOR detector; if ((Table.data == NULL) && (Table.rows*Table.columns)) { detector.m = 0; return(detector); /* Table is empty - nothing to do */ } if (!x1 && !x2) { x1 = Table.min_x; x2 = Table.max_x; } if (!y1 && !y2) { y1 = 1; y2 = Table.columns; } /* transfer content of the Table into a 2D detector */ Coords coords = { 0, 0, 0}; if (Table.rows == 1 || Table.columns == 1) { detector = mcdetector_out_1D(Table.filename, xl ? xl : "", yl ? yl : "", "x", x1, x2, Table.rows * Table.columns, NULL, Table.data, NULL, file, file, coords); } else { detector = mcdetector_out_2D(Table.filename, xl ? xl : "", yl ? yl : "", x1, x2, y1, y2, Table.rows, Table.columns, NULL, Table.data, NULL, file, file, coords); } return(detector); } /****************************************************************************** * void Table_Stat(t_Table *Table) * ACTION: computes min/max/mean step of 1st column for a single table (private) * return: updated Table *******************************************************************************/ static void Table_Stat(t_Table *Table) { long i; double max_x, min_x; double row=1; char monotonic=1; char constantstep=1; double step=0; long n; if (!Table) return; if (!Table->rows || !Table->columns) return; if (Table->rows == 1) row=0; // single row max_x = -FLT_MAX; min_x = FLT_MAX; n = (row ? Table->rows : Table->columns); /* get min and max of first column/vector */ for (i=0; i < n; i++) { double X; X = (row ? Table_Index(*Table,i ,0) : Table_Index(*Table,0, i)); if (X < min_x) min_x = X; if (X > max_x) max_x = X; } /* for */ /* test for monotonicity and constant step if the table is an XY or single vector */ if (n > 1) { /* mean step */ step = (max_x - min_x)/(n-1); /* now test if table is monotonic on first column, and get minimal step size */ for (i=0; i < n-1; i++) { double X, diff;; X = (row ? Table_Index(*Table,i ,0) : Table_Index(*Table,0, i)); diff = (row ? Table_Index(*Table,i+1,0) : Table_Index(*Table,0, i+1)) - X; if (diff && fabs(diff) < fabs(step)) step = diff; /* change sign ? */ if ((max_x - min_x)*diff < 0 && monotonic) monotonic = 0; } /* end for */ /* now test if steps are constant within READ_TABLE_STEPTOL */ if(!step){ /*means there's a disconitnuity -> not constantstep*/ constantstep=0; }else if (monotonic) { for (i=0; i < n-1; i++) { double X, diff; X = (row ? Table_Index(*Table,i ,0) : Table_Index(*Table,0, i)); diff = (row ? Table_Index(*Table,i+1,0) : Table_Index(*Table,0, i+1)) - X; if ( fabs(step)*(1+READ_TABLE_STEPTOL) < fabs(diff) || fabs(diff) < fabs(step)*(1-READ_TABLE_STEPTOL) ) { constantstep = 0; break; } } } } Table->step_x= step; Table->max_x = max_x; Table->min_x = min_x; Table->monotonic = monotonic; Table->constantstep = constantstep; } /* end Table_Stat */ /****************************************************************************** * t_Table *Table_Read_Array(char *File, long *blocks) * ACTION: read as many data blocks as available, iteratively from file * return: initialized t_Table array, last element is an empty Table. * the number of extracted blocks in non NULL pointer *blocks *******************************************************************************/ t_Table *Table_Read_Array(char *File, long *blocks) { t_Table *Table_Array=NULL; long offset=0; long block_number=0; long allocated=256; long nelements=1; /* fisrt allocate an initial empty t_Table array */ Table_Array = (t_Table *)malloc(allocated*sizeof(t_Table)); if (!Table_Array) { fprintf(stderr, "Error: Can not allocate memory %li (Table_Read_Array).\n", allocated*sizeof(t_Table)); *blocks = 0; return (NULL); } while (nelements > 0) { t_Table Table; /* if ok, set t_Table block number else exit loop */ block_number++; Table.block_number = block_number; /* access file at offset and get following block. Block number is from the set offset * hence the hardcoded 1 - i.e. the next block counted from offset.*/ nelements = Table_Read_Offset(&Table, File, 1, &offset,0); /* if t_Table array is not long enough, expand and realocate */ if (block_number >= allocated-1) { allocated += 256; Table_Array = (t_Table *)realloc(Table_Array, allocated*sizeof(t_Table)); if (!Table_Array) { fprintf(stderr, "Error: Can not re-allocate memory %li (Table_Read_Array).\n", allocated*sizeof(t_Table)); *blocks = 0; return (NULL); } } /* store it into t_Table array */ //snprintf(Table.filename, 1024, "%s#%li", File, block_number-1); Table_Array[block_number-1] = Table; /* continues until we find an empty block */ } /* send back number of extracted blocks */ if (blocks) *blocks = block_number-1; /* now store total number of elements in Table array */ for (offset=0; offset < block_number; Table_Array[offset++].array_length = block_number-1); return(Table_Array); } /* end Table_Read_Array */ /******************************************************************************* * void Table_Free_Array(t_Table *Table) * ACTION: free a Table array *******************************************************************************/ void Table_Free_Array(t_Table *Table) { long index=0; if (!Table) return; while (Table[index].data || Table[index].header){ Table_Free(&Table[index]); index++; } free(Table); } /* end Table_Free_Array */ /****************************************************************************** * long Table_Info_Array(t_Table *Table) * ACTION: print informations about a Table array * return: number of elements in the Table array *******************************************************************************/ long Table_Info_Array(t_Table *Table) { long index=0; if (!Table) return(-1); while (index < Table[index].array_length && (Table[index].data || Table[index].header) && (Table[index].rows*Table[index].columns) ) { Table_Info(Table[index]); index++; } printf("This Table array contains %li elements\n", index); return(index); } /* end Table_Info_Array */ /****************************************************************************** * char **Table_ParseHeader(char *header, symbol1, symbol2, ..., NULL) * ACTION: search for char* symbols in header and return their value or NULL * the search is not case sensitive. * Last argument MUST be NULL * return: array of char* with line following each symbol, or NULL if not found *******************************************************************************/ #ifndef MyNL_ARGMAX #define MyNL_ARGMAX 50 #endif char **Table_ParseHeader_backend(char *header, ...){ va_list ap; char exit_flag=0; int counter =0; char **ret =NULL; if (!header || header[0]=='\0') return(NULL); ret = (char**)calloc(MyNL_ARGMAX, sizeof(char*)); if (!ret) { printf("Table_ParseHeader: Cannot allocate %i values array for Parser (Table_ParseHeader).\n", MyNL_ARGMAX); return(NULL); } for (counter=0; counter < MyNL_ARGMAX; ret[counter++] = NULL); counter=0; va_start(ap, header); while(!exit_flag && counter < MyNL_ARGMAX-1) { char *arg_char=NULL; char *pos =NULL; /* get variable argument value as a char */ arg_char = va_arg(ap, char *); if (!arg_char || arg_char[0]=='\0'){ exit_flag = 1; break; } /* search for the symbol in the header */ pos = (char*)strcasestr(header, arg_char); if (pos) { char *eol_pos; eol_pos = strchr(pos+strlen(arg_char), '\n'); if (!eol_pos) eol_pos = strchr(pos+strlen(arg_char), '\r'); if (!eol_pos) eol_pos = pos+strlen(pos)-1; ret[counter] = (char*)malloc(eol_pos - pos); if (!ret[counter]) { printf("Table_ParseHeader: Cannot allocate value[%i] array for Parser searching for %s (Table_ParseHeader).\n", counter, arg_char); exit_flag = 1; break; } strncpy(ret[counter], pos+strlen(arg_char), eol_pos - pos - strlen(arg_char)); ret[counter][eol_pos - pos - strlen(arg_char)]='\0'; } counter++; } va_end(ap); return(ret); } /* Table_ParseHeader */ /****************************************************************************** * double Table_Interp1d(x, x1, y1, x2, y2) * ACTION: interpolates linearly at x between y1=f(x1) and y2=f(x2) * return: y=f(x) value *******************************************************************************/ double Table_Interp1d(double x, double x1, double y1, double x2, double y2) { double slope; if (x2 == x1) return (y1+y2)/2; if (y1 == y2) return y1; slope = (y2 - y1)/(x2 - x1); return y1+slope*(x - x1); } /* Table_Interp1d */ /****************************************************************************** * double Table_Interp1d_nearest(x, x1, y1, x2, y2) * ACTION: table lookup with nearest method at x between y1=f(x1) and y2=f(x2) * return: y=f(x) value *******************************************************************************/ double Table_Interp1d_nearest(double x, double x1, double y1, double x2, double y2) { if (fabs(x-x1) < fabs(x-x2)) return (y1); else return(y2); } /* Table_Interp1d_nearest */ /****************************************************************************** * double Table_Interp2d(x,y, x1,y1, x2,y2, z11,z12,z21,z22) * ACTION: interpolates bi-linearly at (x,y) between z1=f(x1,y1) and z2=f(x2,y2) * return: z=f(x,y) value * x,y | x1 x2 * ---------------- * y1 | z11 z21 * y2 | z12 z22 *******************************************************************************/ double Table_Interp2d(double x, double y, double x1, double y1, double x2, double y2, double z11, double z12, double z21, double z22) { double ratio_x, ratio_y; if (x2 == x1) return Table_Interp1d(y, y1,z11, y2,z12); if (y1 == y2) return Table_Interp1d(x, x1,z11, x2,z21); ratio_y = (y - y1)/(y2 - y1); ratio_x = (x - x1)/(x2 - x1); return (1-ratio_x)*(1-ratio_y)*z11 + ratio_x*(1-ratio_y)*z21 + ratio_x*ratio_y*z22 + (1-ratio_x)*ratio_y*z12; } /* Table_Interp2d */ /* end of read_table-lib.c */ /******************************************************************************* * * McStas, neutron ray-tracing package * Copyright (C) 1997-2008, All rights reserved * Risoe National Laboratory, Roskilde, Denmark * Institut Laue Langevin, Grenoble, France * * Runtime: share/interoff.h * * %Identification * Written by: Reynald Arnerin * Date: Jun 12, 2008 * Release: * Version: * * Object File Format intersection header for McStas. Requires the qsort function. * * Such files may be obtained with e.g. * qhull < points.xyz Qx Qv Tv o > points.off * where points.xyz has format: * 3 * * * ... * The resulting file should have its first line being changed from '3' into 'OFF'. * It can then be displayed with geomview. * A similar, but somewhat older solution is to use 'powercrust' with e.g. * powercrust -i points.xyz * which will generate a 'pc.off' file to be renamed as suited. * *******************************************************************************/ #ifndef INTEROFF_LIB_H #define INTEROFF_LIB_H "$Revision$" #ifndef EPSILON #define EPSILON 1e-13 #endif #define OFF_INTERSECT_MAX 100 //#include #define N_VERTEX_DISPLAYED 200000 typedef struct intersection { MCNUM time; //time of the intersection Coords v; //intersection point Coords normal; //normal vector of the surface intersected short in_out; //1 if the ray enters the volume, -1 otherwise short edge; //1 if the intersection is on the boundary of the polygon, and error is possible unsigned long index; // index of the face } intersection; typedef struct polygon { MCNUM* p; //vertices of the polygon in adjacent order, this way : x1 | y1 | z1 | x2 | y2 | z2 ... int npol; //number of vertices Coords normal; } polygon; typedef struct off_struct { long vtxSize; long polySize; long faceSize; Coords* vtxArray; Coords* normalArray; unsigned long* faceArray; char *filename; int mantidflag; long mantidoffset; intersection intersects[OFF_INTERSECT_MAX]; // After a call to off_intersect_all contains the list of intersections. int nextintersect; // 'Next' intersection (first t>0) solution after call to off_intersect_all int numintersect; // Number of intersections after call to off_intersect_all } off_struct; /******************************************************************************* * long off_init( char *offfile, double xwidth, double yheight, double zdepth, off_struct* data) * ACTION: read an OFF file, optionally center object and rescale, initialize OFF data structure * INPUT: 'offfile' OFF file to read * 'xwidth,yheight,zdepth' if given as non-zero, apply bounding box. * Specifying only one of these will also use the same ratio on all axes * 'notcenter' center the object to the (0,0,0) position in local frame when set to zero * RETURN: number of polyhedra and 'data' OFF structure *******************************************************************************/ long off_init( char *offfile, double xwidth, double yheight, double zdepth, int notcenter, off_struct* data); /******************************************************************************* * int off_intersect_all(double* t0, double* t3, Coords *n0, Coords *n3, double x, double y, double z, double vx, double vy, double vz, off_struct *data ) * ACTION: computes intersection of neutron trajectory with an object. * INPUT: x,y,z and vx,vy,vz are the position and velocity of the neutron * data points to the OFF data structure * RETURN: the number of polyhedra which trajectory intersects * t0 and t3 are the smallest incoming and outgoing intersection times * n0 and n3 are the corresponding normal vectors to the surface * data is the full OFF structure, including a list intersection type *******************************************************************************/ int off_intersect_all(double* t0, double* t3, Coords *n0, Coords *n3, double x, double y, double z, double vx, double vy, double vz, off_struct *data ); /******************************************************************************* * int off_intersect(double* t0, double* t3, Coords *n0, Coords *n3, double x, double y, double z, double vx, double vy, double vz, off_struct data ) * ACTION: computes intersection of neutron trajectory with an object. * INPUT: x,y,z and vx,vy,vz are the position and velocity of the neutron * data points to the OFF data structure * RETURN: the number of polyhedra which trajectory intersects * t0 and t3 are the smallest incoming and outgoing intersection times * n0 and n3 are the corresponding normal vectors to the surface *******************************************************************************/ int off_intersect(double* t0, double* t3, Coords *n0, Coords *n3, double x, double y, double z, double vx, double vy, double vz, off_struct data ); /***************************************************************************** * int off_intersectx(double* l0, double* l3, Coords *n0, Coords *n3, double x, double y, double z, double kx, double ky, double kz, off_struct data ) * ACTION: computes intersection of an xray trajectory with an object. * INPUT: x,y,z and kx,ky,kz, are spatial coordinates and wavevector of the x-ray * respectively. data points to the OFF data structure. * RETURN: the number of polyhedra the trajectory intersects * l0 and l3 are the smallest incoming and outgoing intersection lengths * n0 and n3 are the corresponding normal vectors to the surface *******************************************************************************/ int off_x_intersect(double *l0,double *l3, Coords *n0, Coords *n3, double x, double y, double z, double kx, double ky, double kz, off_struct data ); /******************************************************************************* * void off_display(off_struct data) * ACTION: display up to N_VERTEX_DISPLAYED points from the object *******************************************************************************/ void off_display(off_struct); #endif /* end of interoff-lib.h */ /******************************************************************************* * * McStas, neutron ray-tracing package * Copyright (C) 1997-2008, All rights reserved * Risoe National Laboratory, Roskilde, Denmark * Institut Laue Langevin, Grenoble, France * * Runtime: share/interoff-lib.c * * %Identification * Written by: Reynald Arnerin * Date: Jun 12, 2008 * Origin: ILL * Release: $Revision$ * Version: McStas X.Y * * Object File Format intersection library for McStas. Requires the qsort function. * * Such files may be obtained with e.g. * qhull < points.xyz Qx Qv Tv o > points.off * where points.xyz has format (it supports comments): * 3 * * * ... * The resulting file should have its first line being changed from '3' into 'OFF'. * It can then be displayed with geomview. * A similar, but somewhat older solution is to use 'powercrust' with e.g. * powercrust -i points.xyz * which will generate a 'pc.off' file to be renamed as suited. * *******************************************************************************/ #ifndef INTEROFF_LIB_H #include "interoff-lib.h" #endif double off_F(double x, double y,double z,double A,double B,double C,double D) { return ( A*x + B*y + C*z + D ); } char off_sign(double a) { if (a<0) return(-1); else if (a==0) return(0); else return(1); } // off_normal ****************************************************************** //gives the normal vector of p void off_normal(Coords* n, polygon p) { //using Newell method int i=0,j=0; n->x=0;n->y=0;n->z=0; for (i = 0, j = p.npol-1; i < p.npol; j = i++) { MCNUM x1=p.p[3*i], y1=p.p[3*i+1], z1=p.p[3*i+2]; MCNUM x2=p.p[3*j], y2=p.p[3*j+1], z2=p.p[3*j+2]; // n is the cross product of v1*v2 n->x += (y1 - y2) * (z1 + z2); n->y += (z1 - z2) * (x1 + x2); n->z += (x1 - x2) * (y1 + y2); } } /* off_normal */ // off_pnpoly ****************************************************************** //based on http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html //return 0 if the vertex is out // 1 if it is in // -1 if on the boundary int off_pnpoly(polygon p, Coords v) { int i=0, c = 0; MCNUM minx=FLT_MAX,maxx=-FLT_MAX,miny=FLT_MAX,maxy=-FLT_MAX,minz=FLT_MAX,maxz=-FLT_MAX; MCNUM rangex=0,rangey=0,rangez=0; int pol2dx=0,pol2dy=1; //2d restriction of the poly MCNUM x=v.x,y=v.y; //take the most relevant 2D projection (prevent from instability) for (i=0; imaxx) maxx=p.p[3*i]; if (p.p[3*i+1]maxy) maxy=p.p[3*i+1]; if (p.p[3*i+2]maxz) maxz=p.p[3*i+2]; } rangex=maxx-minx; rangey=maxy-miny; rangez=maxz-minz; if (rangextime = inter->edge = inter->in_out=0; inter->v = inter->normal = coords_set(0,0,1); if (fabs(ndir) < EPSILON) // ray is parallel to polygon plane { if (nw0 == 0) // ray lies in polygon plane (infinite number of solution) return 0; else return 0; // ray disjoint from plane (no solution) } // get intersect point of ray with polygon plane inter->time = nw0 / ndir; //parametric value the point on line (a,b) inter->v = coords_set(a.x + inter->time * dir.x,// intersect point of ray and plane a.y + inter->time * dir.y, a.z + inter->time * dir.z); int res=off_pnpoly(p,inter->v); inter->edge=(res==-1); if (ndir<0) inter->in_out=1; //the negative dot product means we enter the surface else inter->in_out=-1; inter->normal=p.normal; return res; //true if the intersection point lies inside the poly } /* off_intersectPoly */ // off_getBlocksIndex ********************************************************** /*reads the indexes at the beginning of the off file as this : line 1 OFF line 2 nbVertex nbFaces nbEdges */ FILE *off_getBlocksIndex(char* filename, long* vtxSize, long* polySize ) { FILE* f = Open_File(filename,"r", NULL); /* from read_table-lib: FILE *Open_File(char *name, char *Mode, char *path) */ if (!f) return (f); char line[CHAR_BUF_LENGTH]; char *ret=0; *vtxSize = *polySize = 0; /* **************** start to read the file header */ /* OFF file: 'OFF' or '3' */ ret=fgets(line,CHAR_BUF_LENGTH , f);// line 1 = "OFF" if (ret == NULL) { fprintf(stderr, "Error: Can not read 1st line in file %s (interoff/off_getBlocksIndex)\n", filename); exit(1); } if (strncmp(line,"OFF",3) && strncmp(line,"3",1) && strncmp(line,"ply",1)) { fprintf(stderr, "Error: %s is probably not an OFF, NOFF or PLY file (interoff/off_getBlocksIndex).\n" " Requires first line to be 'OFF', '3' or 'ply'.\n",filename); fclose(f); return(NULL); } if (!strncmp(line,"OFF",3) || !strncmp(line,"3",1)) { do /* OFF file: skip # comments which may be there */ { ret=fgets(line,CHAR_BUF_LENGTH , f); if (ret == NULL) { fprintf(stderr, "Error: Can not read line in file %s (interoff/off_getBlocksIndex)\n", filename); exit(1); } } while (line[0]=='#'); //line = nblines of vertex,faces and edges arrays sscanf(line,"%lu %lu",vtxSize,polySize); } else { do /* PLY file: read all lines until find 'end_header' and locate 'element faces' and 'element vertex' */ { ret=fgets(line,CHAR_BUF_LENGTH , f); if (ret == NULL) { fprintf(stderr, "Error: Can not read line in file %s (interoff/off_getBlocksIndex)\n", filename); exit(1); } if (!strncmp(line,"element face",12)) sscanf(line,"element face %lu",polySize); else if (!strncmp(line,"element vertex",14)) sscanf(line,"element vertex %lu",vtxSize); else if (!strncmp(line,"format binary",13)) exit(fprintf(stderr, "Error: Can not read binary PLY file %s, only 'format ascii' (interoff/off_getBlocksIndex)\n%s\n", filename, line)); } while (strncmp(line,"end_header",10)); } /* The FILE is left opened ready to read 'vtxSize' vertices (vtxSize *3 numbers) and then polySize polygons (rows) */ return(f); } /* off_getBlocksIndex */ // off_init_planes ************************************************************* //gives the equations of 2 perpandicular planes of [ab] void off_init_planes(Coords a, Coords b, MCNUM* A1, MCNUM* C1, MCNUM* D1, MCNUM *A2, MCNUM* B2, MCNUM* C2, MCNUM* D2) { //direction vector of [a b] Coords dir={b.x-a.x, b.y-a.y, b.z-a.z}; //the plane parallel to the 'y' is computed with the normal vector of the projection of [ab] on plane 'xz' *A1= dir.z; *C1=-dir.x; if(*A1!=0 || *C1!=0) *D1=-(a.x)*(*A1)-(a.z)*(*C1); else { //the plane does not support the vector, take the one parallel to 'z'' *A1=1; //B1=dir.x=0 *D1=-(a.x); } //the plane parallel to the 'x' is computed with the normal vector of the projection of [ab] on plane 'yz' *B2= dir.z; *C2=-dir.y; *A2= 0; if (*B2==0 && *C2==0) { //the plane does not support the vector, take the one parallel to 'z' *B2=1; //B1=dir.x=0 *D2=-(a.y); } else { if (dir.z==0) { //the planes are the same, take the one parallel to 'z' *A2= dir.y; *B2=-dir.x; *D2=-(a.x)*(*A2)-(a.y)*(*B2); } else *D2=-(a.y)**B2-(a.z)**C2; } } /* off_init_planes */ // off_clip_3D_mod ************************************************************* int off_clip_3D_mod(intersection* t, Coords a, Coords b, Coords* vtxArray, unsigned long vtxSize, unsigned long* faceArray, unsigned long faceSize, Coords* normalArray) { MCNUM A1=0, C1=0, D1=0, A2=0, B2=0, C2=0, D2=0; //perpendicular plane equations to [a,b] off_init_planes(a, b, &A1, &C1, &D1, &A2, &B2, &C2, &D2); int t_size=0; //unsigned long vtxSize=vtxTable.rows, faceSize=faceTable.columns; //Size of the corresponding tables char sg[vtxSize]; //array telling if vertex is left or right of the plane MCNUM popol[3*CHAR_BUF_LENGTH]; unsigned long i=0,indPoly=0; for (i=0; i < vtxSize; ++i) { sg[i]=off_sign(off_F(vtxArray[i].x,vtxArray[i].y,vtxArray[i].z,A1,0,C1,D1)); } //exploring the polygons : i=indPoly=0; while (iCHAR_BUF_LENGTH) { fprintf(stderr, "Warning: number of intersection exceeded (%d) (interoff-lib/off_clip_3D_mod)\n", CHAR_BUF_LENGTH); return (t_size); } //both planes intersect the polygon, let's find the intersection point //our polygon : int k; for (k=0; ktime - pb->time); } /* off_compare */ // off_cleanDouble ************************************************************* //given an array of intersections throw those which appear several times //returns 1 if there is a possibility of error int off_cleanDouble(intersection* t, int* t_size) { int i=1; intersection prev=t[0]; while (i<*t_size) { int j=i; //for each intersection with the same time while (j<*t_size && fabs(prev.time-t[j].time)maxx) maxx=vtxArray[i].x; if (vtxArray[i].ymaxy) maxy=vtxArray[i].y; if (vtxArray[i].zmaxz) maxz=vtxArray[i].z; i++; // inquire next vertex } // resizing and repositioning params double centerx=0, centery=0, centerz=0; if (!notcenter) { centerx=(minx+maxx)*0.5; centery=(miny+maxy)*0.5; centerz=(minz+maxz)*0.5; } double rangex=-minx+maxx, rangey=-miny+maxy, rangez=-minz+maxz; double ratiox=1,ratioy=1,ratioz=1; if (xwidth && rangex) { ratiox=xwidth/rangex; ratioy=ratiox; ratioz=ratiox; } if (yheight && rangey) { ratioy=yheight/rangey; if(!xwidth) ratiox=ratioy; ratioz=ratioy; } if (zdepth && rangez) { ratioz=zdepth/rangez; if(!xwidth) ratiox=ratioz; if(!yheight) ratioy=ratioz; } rangex *= ratiox; rangey *= ratioy; rangez *= ratioz; //center and resize the object for (i=0; i polySize*10) { fprintf(stderr, "Error: %li exceeded allocated polygon array[%li] in file %s (interoff/off_init)\n", faceSize, polySize*10, offfile); } faceArray[faceSize++] = nbVertex; // length of the polygon/face // then read the vertex ID's for (j=0; jvtxArray = vtxArray; data->normalArray= normalArray; data->faceArray = faceArray; data->vtxSize = vtxSize; data->polySize = polySize; data->faceSize = faceSize; data->filename = offfile; return(polySize); } /* off_init */ /******************************************************************************* * int off_intersect_all(double* t0, double* t3, Coords *n0, Coords *n3, double x, double y, double z, double vx, double vy, double vz, off_struct *data ) * ACTION: computes intersection of neutron trajectory with an object. * INPUT: x,y,z and vx,vy,vz are the position and velocity of the neutron * data points to the OFF data structure * RETURN: the number of polyhedra which trajectory intersects * t0 and t3 are the smallest incoming and outgoing intersection times * n0 and n3 are the corresponding normal vectors to the surface * data is the full OFF structure, including a list intersection type *******************************************************************************/ int off_intersect_all(double* t0, double* t3, Coords *n0, Coords *n3, double x, double y, double z, double vx, double vy, double vz, off_struct *data ) { Coords A={x, y, z}; Coords B={x+vx, y+vy, z+vz}; int t_size=off_clip_3D_mod(data->intersects, A, B, data->vtxArray, data->vtxSize, data->faceArray, data->faceSize, data->normalArray ); qsort(data->intersects, t_size, sizeof(intersection), off_compare); off_cleanDouble(data->intersects, &t_size); off_cleanInOut(data->intersects, &t_size); /*find intersections "closest" to 0 (favouring positive ones)*/ if(t_size>0){ int i=0; if(t_size>1) { for (i=1; i < t_size-1; i++){ if (data->intersects[i-1].time > 0 && data->intersects[i].time > 0) break; } data->nextintersect=i-1; data->numintersect=t_size; if (t0) *t0 = data->intersects[i-1].time; if (n0) *n0 = data->intersects[i-1].normal; if (t3) *t3 = data->intersects[i].time; if (n3) *n3 = data->intersects[i].normal; } else { if (t0) *t0 = data->intersects[0].time; if (n0) *n0 = data->intersects[0].normal; } /* should also return t[0].index and t[i].index as polygon ID */ return t_size; } return 0; } /* off_intersect */ /******************************************************************************* * int off_intersect(double* t0, double* t3, Coords *n0, Coords *n3, double x, double y, double z, double vx, double vy, double vz, off_struct data ) * ACTION: computes intersection of neutron trajectory with an object. * INPUT: x,y,z and vx,vy,vz are the position and velocity of the neutron * data points to the OFF data structure * RETURN: the number of polyhedra which trajectory intersects * t0 and t3 are the smallest incoming and outgoing intersection times * n0 and n3 are the corresponding normal vectors to the surface *******************************************************************************/ int off_intersect(double* t0, double* t3, Coords *n0, Coords *n3, double x, double y, double z, double vx, double vy, double vz, off_struct data ) { return off_intersect_all(t0, t3, n0, n3, x, y, z, vx, vy, vz, &data ); } /* off_intersect */ /***************************************************************************** * int off_x_intersect(double* l0, double* l3, Coords *n0, Coords *n3, double x, double y, double z, double kx, double ky, double kz, off_struct data ) * ACTION: computes intersection of an xray trajectory with an object. * INPUT: x,y,z and kx,ky,kz, are spatial coordinates and wavevector of the x-ray * respectively. data points to the OFF data structure. * RETURN: the number of polyhedra the trajectory intersects * l0 and l3 are the smallest incoming and outgoing intersection lengths * n0 and n3 are the corresponding normal vectors to the surface *******************************************************************************/ int off_x_intersect(double *l0,double *l3, Coords *n0, Coords *n3, double x, double y, double z, double kx, double ky, double kz, off_struct data ) { /*This function simply reformats and calls off_intersect (as for neutrons) *by normalizing the wavevector - this will yield the intersection lengths *in m*/ double jx,jy,jz,invk; int n; invk=1/sqrt(scalar_prod(kx,ky,kz,kx,ky,kz)); jx=kx*invk;jy=ky*invk;jz=kz*invk; n=off_intersect(l0,l3,n0,n3,x,y,z,jx,jy,jz,data); return n; } /******************************************************************************* * void off_display(off_struct data) * ACTION: display up to N_VERTEX_DISPLAYED polygons from the object *******************************************************************************/ void off_display(off_struct data) { unsigned int i; double ratio=(double)(N_VERTEX_DISPLAYED)/(double)data.faceSize; unsigned int pixel=0; for (i=0; i 1 || drawthis) { mcdis_line(x1,y1,z1,x2,y2,z2); } x1 = x2; y1 = y2; z1 = z2; } if (ratio > 1 || drawthis) { mcdis_line(x1,y1,z1,x0,y0,z0); } if (data.mantidflag) { printf("MANTID_PIXEL: %s\n", pixelinfo); pixel++; } i += nbVertex; } } /* off_display */ /* end of interoff-lib.c */ enum StrainDistribution { AxialSym1D, /* 1D axial symmetric, i.e. cylinder sample with strain gradient along radius */ AxialSym2D /* 2D axial symmetric, i.e. cylinder sample with strain gradient along radius and along height */ /*NoSym1D*/ }; typedef struct { /** values from FILE **/ /* strains in the sample represented by lattice spacing */ int n_entries; /* number of entries for hoop, radial, axial */ double *pos_x; /* lists of all positions */ double *pos_y; double *pos_z; double *strains_hoop; /* lists of all strain values */ double *strains_radial; double *strains_axial; double d0_hoop; /* reference values */ double d0_radial; double d0_axial; enum StrainDistribution strain_distr; /* strain distribution mode */ } StrainData; int readStrainFile( char *fileName, StrainData *sd ) { /* read the file */ t_Table dataTable; Table_Read(&dataTable, fileName, 1); /* read 1st block data from file into table */ int i; char **parsing; /* some default values to check if input file is consistent */ int column_radius = 0; int column_height = 0; int column_hoop = 0; int column_radial = 0; int column_axial = 0; sd->d0_hoop = sd->d0_radial = sd->d0_axial = 0.0; /* parsing of header for sample parameters */ parsing = Table_ParseHeader( dataTable.header,"d0_hoop","d0_radial","d0_axial",NULL ); if (parsing) { if( parsing[0] ) sd->d0_hoop = atof(parsing[0]); else { fprintf(stderr, "%s: Warning: No value for 'd0_hoop' found in file %s\n", NAME_CURRENT_COMP, fileName); } if( parsing[1] ) sd->d0_radial = atof(parsing[1]); else { fprintf(stderr, "%s: Warning: No value for 'd0_radial' found in file %s\n", NAME_CURRENT_COMP, fileName); } if( parsing[2] ) sd->d0_axial = atof(parsing[2]); else { fprintf(stderr, "%s: Warning: No value for 'd0_axial' found in file %s\n", NAME_CURRENT_COMP, fileName); } } else { fprintf(stderr, "%s: Warning: parsing file %s\n", NAME_CURRENT_COMP, fileName); return -1; } /* parsing of header for column assignment */ parsing = Table_ParseHeader(dataTable.header, "column_radius", "column_height","column_hoop","column_radial","column_axial",NULL); /* assign columns */ if (parsing) { if (parsing[0]) column_radius = atoi(parsing[0]); if (parsing[1]) column_height = atoi(parsing[1]); if (parsing[2]) column_hoop = atoi(parsing[2]); if (parsing[3]) column_radial = atoi(parsing[3]); if (parsing[4]) column_axial = atoi(parsing[4]); for (i=0; i<5; i++) if (parsing[i]) free(parsing[i]); free(parsing); /* decide which strain distribution is stored in the file */ int minimum_columns = 4; if( column_radius ) { sd->strain_distr = AxialSym1D; minimum_columns = 4; } if( column_radius && column_height ) { sd->strain_distr = AxialSym2D; minimum_columns = 5; } /* check if data exists (at least minimum number of columns) */ if( dataTable.columns < minimum_columns ) { fprintf(stderr, "%s: Error: There are too few table columns in '%s' to process strain data - using default values now\n", NAME_CURRENT_COMP, fileName); sd->n_entries = 0; return -1; } /* allocate data array */ sd->pos_x = (double*)malloc(dataTable.rows*sizeof(double)); if( sd->strain_distr == AxialSym2D ) sd->pos_y = (double*)malloc(dataTable.rows*sizeof(double)); sd->strains_hoop = (double*)malloc(dataTable.rows*sizeof(double)); sd->strains_radial = (double*)malloc(dataTable.rows*sizeof(double)); sd->strains_axial = (double*)malloc(dataTable.rows*sizeof(double)); sd->n_entries = dataTable.rows; /* get data from table */ struct list_struct{ double pos_x; double pos_y; double hoop; double radial; double axial; }; struct list_struct* dataList = (struct list_struct*)malloc( sizeof(struct list_struct)*sd->n_entries ); for (i=0; in_entries; i++) { dataList[i].pos_x = Table_Index(dataTable, i, column_radius-1); if( sd->strain_distr == AxialSym2D ) dataList[i].pos_y = Table_Index(dataTable, i, column_height-1); dataList[i].hoop = Table_Index(dataTable, i, column_hoop-1); dataList[i].radial = Table_Index(dataTable, i, column_radial-1); dataList[i].axial = Table_Index(dataTable, i, column_axial-1); } /* sort list by position */ int pos_x_compare( const void *par1, const void *par2) { return ( ((struct list_struct*)par1)->pos_x<((struct list_struct*)par2)->pos_x ) ? 0 : 1; } /* (re-)sort the data set to evaluate it in the TRACE section */ qsort( dataList, dataTable.rows, sizeof(struct list_struct), pos_x_compare ); if( sd->strain_distr == AxialSym2D ) { int pos_y_compare( const void *par1, const void *par2) { return ( ((struct list_struct*)par1)->pos_y<((struct list_struct*)par2)->pos_y ) ? 0 : 1; } qsort( dataList, dataTable.rows, sizeof(struct list_struct), pos_y_compare ); } for (i=0; in_entries; i++) { sd->pos_x[i] = dataList[i].pos_x; if( sd->strain_distr == AxialSym2D ) sd->pos_y[i] = dataList[i].pos_y; sd->strains_hoop[i] = dataList[i].hoop; sd->strains_radial[i] = dataList[i].radial; sd->strains_axial[i] = dataList[i].axial; } /* data set is now sorted */ } return 0; } #line 8878 "tof_diffraction.c" /* Instrument parameters. */ MCNUM mciplambda1; MCNUM mciplambda2; MCNUM mcipsample_detector_distance; MCNUM mcipmoderator_pinhole_distance; MCNUM mcippinhole_sample_distance; MCNUM mcipsample_x; MCNUM mcipthickness; char* mcipsample_file; char* mcipmoderator_face; #define mcNUMIPAR 9 int mcnumipar = 9; struct mcinputtable_struct mcinputtable[mcNUMIPAR+1] = { "lambda1", &mciplambda1, instr_type_double, "1.5", "lambda2", &mciplambda2, instr_type_double, "1.51", "sample_detector_distance", &mcipsample_detector_distance, instr_type_double, "0.1", "moderator_pinhole_distance", &mcipmoderator_pinhole_distance, instr_type_double, "30.0", "pinhole_sample_distance", &mcippinhole_sample_distance, instr_type_double, "0.05", "sample_x", &mcipsample_x, instr_type_double, "0.0", "thickness", &mcipthickness, instr_type_double, "0.005", "sample_file", &mcipsample_file, instr_type_string, "Fe.nxs", "moderator_face", &mcipmoderator_face, instr_type_string, "water", NULL, NULL, instr_type_double, "" }; /* User declarations from instrument definition. */ #define mccompcurname tof_diffraction #define mccompcurtype INSTRUMENT #define mccompcurindex 0 #define mcposatof_diffraction coords_set(0,0,0) #define lambda1 mciplambda1 #define lambda2 mciplambda2 #define sample_detector_distance mcipsample_detector_distance #define moderator_pinhole_distance mcipmoderator_pinhole_distance #define pinhole_sample_distance mcippinhole_sample_distance #define sample_x mcipsample_x #define thickness mcipthickness #define sample_file mcipsample_file #define moderator_face mcipmoderator_face #undef moderator_face #undef sample_file #undef thickness #undef sample_x #undef pinhole_sample_distance #undef moderator_pinhole_distance #undef sample_detector_distance #undef lambda2 #undef lambda1 #undef mcposatof_diffraction #undef mccompcurindex #undef mccompcurtype #undef mccompcurname /* neutron state table at each component input (local coords) */ /* [x, y, z, vx, vy, vz, t, sx, sy, sz, p] */ MCNUM mccomp_storein[11*13]; /* Components position table (absolute and relative coords) */ Coords mccomp_posa[13]; Coords mccomp_posr[13]; /* Counter for each comp to check for inactive ones */ MCNUM mcNCounter[13]; MCNUM mcPCounter[13]; MCNUM mcP2Counter[13]; #define mcNUMCOMP 12 /* number of components */ /* Counter for PROP ABSORB */ MCNUM mcAbsorbProp[13]; /* Flag true when previous component acted on the neutron (SCATTER) */ MCNUM mcScattered=0; /* Flag true when neutron should be restored (RESTORE) */ MCNUM mcRestore=0; /* Declarations of component definition and setting parameters. */ /* Definition parameters for component 'moderator' [2]. */ #define mccmoderator_Face mcipmoderator_face /* declared as a string. May produce warnings at compile */ /* Setting parameters for component 'moderator' [2]. */ MCNUM mccmoderator_Emin; MCNUM mccmoderator_Emax; MCNUM mccmoderator_dist; MCNUM mccmoderator_focus_xw; MCNUM mccmoderator_focus_yh; MCNUM mccmoderator_xwidth; MCNUM mccmoderator_yheight; MCNUM mccmoderator_CAngle; MCNUM mccmoderator_SAC; MCNUM mccmoderator_Lmin; MCNUM mccmoderator_Lmax; int mccmoderator_target_index; MCNUM mccmoderator_verbose; /* Setting parameters for component 'pinhole' [3]. */ MCNUM mccpinhole_xmin; MCNUM mccpinhole_xmax; MCNUM mccpinhole_ymin; MCNUM mccpinhole_ymax; MCNUM mccpinhole_radius; MCNUM mccpinhole_xwidth; MCNUM mccpinhole_yheight; /* Definition parameters for component 'sample1' [4]. */ #define mccsample1_TransOnly 0 #define mccsample1_IncohScat 1 #define mccsample1_MultiScat 0 /* Setting parameters for component 'sample1' [4]. */ MCNUM mccsample1_xwidth; MCNUM mccsample1_yheight; MCNUM mccsample1_zthick; MCNUM mccsample1_radius; MCNUM mccsample1_thickness; char mccsample1_geometry[16384]; char mccsample1_nxsFileName[16384]; int mccsample1_max_hkl; MCNUM mccsample1_d_phi; char mccsample1_strainFileName[16384]; MCNUM mccsample1_sample_temp; /* Setting parameters for component 'beamstop' [6]. */ MCNUM mccbeamstop_xmin; MCNUM mccbeamstop_xmax; MCNUM mccbeamstop_ymin; MCNUM mccbeamstop_ymax; MCNUM mccbeamstop_xwidth; MCNUM mccbeamstop_yheight; MCNUM mccbeamstop_radius; /* Definition parameters for component 'tofmon' [7]. */ #define mcctofmon_nt 600 /* Setting parameters for component 'tofmon' [7]. */ char mcctofmon_filename[16384]; MCNUM mcctofmon_xmin; MCNUM mcctofmon_xmax; MCNUM mcctofmon_ymin; MCNUM mcctofmon_ymax; MCNUM mcctofmon_xwidth; MCNUM mcctofmon_yheight; MCNUM mcctofmon_tmin; MCNUM mcctofmon_tmax; MCNUM mcctofmon_dt; MCNUM mcctofmon_restore_neutron; /* Definition parameters for component 'lmon' [8]. */ #define mcclmon_nL 500 /* Setting parameters for component 'lmon' [8]. */ char mcclmon_filename[16384]; MCNUM mcclmon_xmin; MCNUM mcclmon_xmax; MCNUM mcclmon_ymin; MCNUM mcclmon_ymax; MCNUM mcclmon_xwidth; MCNUM mcclmon_yheight; MCNUM mcclmon_Lmin; MCNUM mcclmon_Lmax; MCNUM mcclmon_restore_neutron; /* Setting parameters for component 'blende' [10]. */ MCNUM mccblende_xmin; MCNUM mccblende_xmax; MCNUM mccblende_ymin; MCNUM mccblende_ymax; MCNUM mccblende_radius; MCNUM mccblende_xwidth; MCNUM mccblende_yheight; /* Definition parameters for component 'detector' [11]. */ #define mccdetector_nx 500 #define mccdetector_ny 500 /* Setting parameters for component 'detector' [11]. */ char mccdetector_filename[16384]; MCNUM mccdetector_xmin; MCNUM mccdetector_xmax; MCNUM mccdetector_ymin; MCNUM mccdetector_ymax; MCNUM mccdetector_xwidth; MCNUM mccdetector_yheight; MCNUM mccdetector_restore_neutron; /* User component declarations. */ /* User declarations for component 'a1' [1]. */ #define mccompcurname a1 #define mccompcurtype Arm #define mccompcurindex 1 #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'moderator' [2]. */ #define mccompcurname moderator #define mccompcurtype ISIS_moderator #define mccompcurindex 2 #define Face mccmoderator_Face #define p_in mccmoderator_p_in #define Tnpts mccmoderator_Tnpts #define scaleSize mccmoderator_scaleSize #define angleArea mccmoderator_angleArea #define Nsim mccmoderator_Nsim #define Ncount mccmoderator_Ncount #define TS mccmoderator_TS #define rtE0 mccmoderator_rtE0 #define rtE1 mccmoderator_rtE1 #define rtmodX mccmoderator_rtmodX #define rtmodY mccmoderator_rtmodY #define TargetStation mccmoderator_TargetStation #define CurrentWeight mccmoderator_CurrentWeight #define Emin mccmoderator_Emin #define Emax mccmoderator_Emax #define dist mccmoderator_dist #define focus_xw mccmoderator_focus_xw #define focus_yh mccmoderator_focus_yh #define xwidth mccmoderator_xwidth #define yheight mccmoderator_yheight #define CAngle mccmoderator_CAngle #define SAC mccmoderator_SAC #define Lmin mccmoderator_Lmin #define Lmax mccmoderator_Lmax #define target_index mccmoderator_target_index #define verbose mccmoderator_verbose #line 815 "/mnt/lustre/apps/centos73/mcstas/2.4.1/contrib/ISIS_moderator.comp" #include /* global variables */ double p_in; /* Polorization term (from McSTAS) */ int Tnpts; /* Number of points in parameteriation */ double scaleSize; /* correction for the actual area of the moderator viewed */ double angleArea; /* Area seen by the window */ double Nsim; /* Total number of neutrons to be simulated */ int Ncount; /* Number of neutron simulate so far*/ Source TS; /* runtime variables*/ double rtE0,rtE1; /* runtime Energy minima and maxima so we can use angstroms as negative input */ double rtmodX,rtmodY; /* runtime moderator sizes, so that a negative argument may give a default size */ int TargetStation; double CurrentWeight; #line 9116 "tof_diffraction.c" #undef verbose #undef target_index #undef Lmax #undef Lmin #undef SAC #undef CAngle #undef yheight #undef xwidth #undef focus_yh #undef focus_xw #undef dist #undef Emax #undef Emin #undef CurrentWeight #undef TargetStation #undef rtmodY #undef rtmodX #undef rtE1 #undef rtE0 #undef TS #undef Ncount #undef Nsim #undef angleArea #undef scaleSize #undef Tnpts #undef p_in #undef Face #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'pinhole' [3]. */ #define mccompcurname pinhole #define mccompcurtype Slit #define mccompcurindex 3 #define xmin mccpinhole_xmin #define xmax mccpinhole_xmax #define ymin mccpinhole_ymin #define ymax mccpinhole_ymax #define radius mccpinhole_radius #define xwidth mccpinhole_xwidth #define yheight mccpinhole_yheight #undef yheight #undef xwidth #undef radius #undef ymax #undef ymin #undef xmax #undef xmin #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'sample1' [4]. */ #define mccompcurname sample1 #define mccompcurtype sample_nxs #define mccompcurindex 4 #define TransOnly mccsample1_TransOnly #define IncohScat mccsample1_IncohScat #define MultiScat mccsample1_MultiScat #define isrect mccsample1_isrect #define intersect mccsample1_intersect #define nxs_init_success mccsample1_nxs_init_success #define p_transmit mccsample1_p_transmit #define xsect_total mccsample1_xsect_total #define xsect_coherent mccsample1_xsect_coherent #define xsect_incoherent mccsample1_xsect_incoherent #define xsect_absorption mccsample1_xsect_absorption #define lambda mccsample1_lambda #define velocity mccsample1_velocity #define fullpath mccsample1_fullpath #define t1 mccsample1_t1 #define t2 mccsample1_t2 #define uc mccsample1_uc #define A mccsample1_A #define mu_factor mccsample1_mu_factor #define sd mccsample1_sd #define V2L mccsample1_V2L #define xwidth mccsample1_xwidth #define yheight mccsample1_yheight #define zthick mccsample1_zthick #define radius mccsample1_radius #define thickness mccsample1_thickness #define geometry mccsample1_geometry #define nxsFileName mccsample1_nxsFileName #define max_hkl mccsample1_max_hkl #define d_phi mccsample1_d_phi #define strainFileName mccsample1_strainFileName #define sample_temp mccsample1_sample_temp #line 322 "sample_nxs.comp" int shape; off_struct offdata; int nxs_init_success; /* cross sections */ double xsect_coherent; double xsect_incoherent; double xsect_absorption; /* sample */ NXS_UnitCell uc; StrainData sd; /* velocity to lambda conversion */ double V2L; #line 9224 "tof_diffraction.c" #undef sample_temp #undef strainFileName #undef d_phi #undef max_hkl #undef nxsFileName #undef geometry #undef thickness #undef radius #undef zthick #undef yheight #undef xwidth #undef V2L #undef sd #undef mu_factor #undef A #undef uc #undef t2 #undef t1 #undef fullpath #undef velocity #undef lambda #undef xsect_absorption #undef xsect_incoherent #undef xsect_coherent #undef xsect_total #undef p_transmit #undef nxs_init_success #undef intersect #undef isrect #undef MultiScat #undef IncohScat #undef TransOnly #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'sample' [5]. */ #define mccompcurname sample #define mccompcurtype Arm #define mccompcurindex 5 #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'beamstop' [6]. */ #define mccompcurname beamstop #define mccompcurtype Beamstop #define mccompcurindex 6 #define xmin mccbeamstop_xmin #define xmax mccbeamstop_xmax #define ymin mccbeamstop_ymin #define ymax mccbeamstop_ymax #define xwidth mccbeamstop_xwidth #define yheight mccbeamstop_yheight #define radius mccbeamstop_radius #undef radius #undef yheight #undef xwidth #undef ymax #undef ymin #undef xmax #undef xmin #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'tofmon' [7]. */ #define mccompcurname tofmon #define mccompcurtype TOF_monitor #define mccompcurindex 7 #define nt mcctofmon_nt #define TOF_N mcctofmon_TOF_N #define TOF_p mcctofmon_TOF_p #define TOF_p2 mcctofmon_TOF_p2 #define t_min mcctofmon_t_min #define t_max mcctofmon_t_max #define delta_t mcctofmon_delta_t #define filename mcctofmon_filename #define xmin mcctofmon_xmin #define xmax mcctofmon_xmax #define ymin mcctofmon_ymin #define ymax mcctofmon_ymax #define xwidth mcctofmon_xwidth #define yheight mcctofmon_yheight #define tmin mcctofmon_tmin #define tmax mcctofmon_tmax #define dt mcctofmon_dt #define restore_neutron mcctofmon_restore_neutron #line 53 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/TOF_monitor.comp" double TOF_N[nt]; double TOF_p[nt]; double TOF_p2[nt]; double t_min, t_max, delta_t; #line 9318 "tof_diffraction.c" #undef restore_neutron #undef dt #undef tmax #undef tmin #undef yheight #undef xwidth #undef ymax #undef ymin #undef xmax #undef xmin #undef filename #undef delta_t #undef t_max #undef t_min #undef TOF_p2 #undef TOF_p #undef TOF_N #undef nt #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'lmon' [8]. */ #define mccompcurname lmon #define mccompcurtype L_monitor #define mccompcurindex 8 #define nL mcclmon_nL #define L_N mcclmon_L_N #define L_p mcclmon_L_p #define L_p2 mcclmon_L_p2 #define filename mcclmon_filename #define xmin mcclmon_xmin #define xmax mcclmon_xmax #define ymin mcclmon_ymin #define ymax mcclmon_ymax #define xwidth mcclmon_xwidth #define yheight mcclmon_yheight #define Lmin mcclmon_Lmin #define Lmax mcclmon_Lmax #define restore_neutron mcclmon_restore_neutron #line 56 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/L_monitor.comp" double L_N[nL]; double L_p[nL], L_p2[nL]; #line 9362 "tof_diffraction.c" #undef restore_neutron #undef Lmax #undef Lmin #undef yheight #undef xwidth #undef ymax #undef ymin #undef xmax #undef xmin #undef filename #undef L_p2 #undef L_p #undef L_N #undef nL #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'rot90' [9]. */ #define mccompcurname rot90 #define mccompcurtype Arm #define mccompcurindex 9 #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'blende' [10]. */ #define mccompcurname blende #define mccompcurtype Slit #define mccompcurindex 10 #define xmin mccblende_xmin #define xmax mccblende_xmax #define ymin mccblende_ymin #define ymax mccblende_ymax #define radius mccblende_radius #define xwidth mccblende_xwidth #define yheight mccblende_yheight #undef yheight #undef xwidth #undef radius #undef ymax #undef ymin #undef xmax #undef xmin #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* User declarations for component 'detector' [11]. */ #define mccompcurname detector #define mccompcurtype PSD_monitor #define mccompcurindex 11 #define nx mccdetector_nx #define ny mccdetector_ny #define PSD_N mccdetector_PSD_N #define PSD_p mccdetector_PSD_p #define PSD_p2 mccdetector_PSD_p2 #define filename mccdetector_filename #define xmin mccdetector_xmin #define xmax mccdetector_xmax #define ymin mccdetector_ymin #define ymax mccdetector_ymax #define xwidth mccdetector_xwidth #define yheight mccdetector_yheight #define restore_neutron mccdetector_restore_neutron #line 55 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/PSD_monitor.comp" double PSD_N[nx][ny]; double PSD_p[nx][ny]; double PSD_p2[nx][ny]; #line 9432 "tof_diffraction.c" #undef restore_neutron #undef yheight #undef xwidth #undef ymax #undef ymin #undef xmax #undef xmin #undef filename #undef PSD_p2 #undef PSD_p #undef PSD_N #undef ny #undef nx #undef mccompcurname #undef mccompcurtype #undef mccompcurindex Coords mcposaa1, mcposra1; Rotation mcrotaa1, mcrotra1; Coords mcposamoderator, mcposrmoderator; Rotation mcrotamoderator, mcrotrmoderator; Coords mcposapinhole, mcposrpinhole; Rotation mcrotapinhole, mcrotrpinhole; Coords mcposasample1, mcposrsample1; Rotation mcrotasample1, mcrotrsample1; Coords mcposasample, mcposrsample; Rotation mcrotasample, mcrotrsample; Coords mcposabeamstop, mcposrbeamstop; Rotation mcrotabeamstop, mcrotrbeamstop; Coords mcposatofmon, mcposrtofmon; Rotation mcrotatofmon, mcrotrtofmon; Coords mcposalmon, mcposrlmon; Rotation mcrotalmon, mcrotrlmon; Coords mcposarot90, mcposrrot90; Rotation mcrotarot90, mcrotrrot90; Coords mcposablende, mcposrblende; Rotation mcrotablende, mcrotrblende; Coords mcposadetector, mcposrdetector; Rotation mcrotadetector, mcrotrdetector; MCNUM mcnx, mcny, mcnz, mcnvx, mcnvy, mcnvz, mcnt, mcnsx, mcnsy, mcnsz, mcnp; /* end declare */ void mcinit(void) { #define mccompcurname tof_diffraction #define mccompcurtype INSTRUMENT #define mccompcurindex 0 #define mcposatof_diffraction coords_set(0,0,0) #define lambda1 mciplambda1 #define lambda2 mciplambda2 #define sample_detector_distance mcipsample_detector_distance #define moderator_pinhole_distance mcipmoderator_pinhole_distance #define pinhole_sample_distance mcippinhole_sample_distance #define sample_x mcipsample_x #define thickness mcipthickness #define sample_file mcipsample_file #define moderator_face mcipmoderator_face #line 15 "tof_diffraction.instr" { } #line 9495 "tof_diffraction.c" #undef moderator_face #undef sample_file #undef thickness #undef sample_x #undef pinhole_sample_distance #undef moderator_pinhole_distance #undef sample_detector_distance #undef lambda2 #undef lambda1 #undef mcposatof_diffraction #undef mccompcurindex #undef mccompcurtype #undef mccompcurname /* Computation of coordinate transformations. */ { Coords mctc1, mctc2, mcLastComp; Rotation mctr1; double mcAccumulatedILength = 0; /* Initialize "last" component origin as (0,0,0) */ mcLastComp = coords_set(0,0,0); mcDEBUG_INSTR() /* Component initializations. */ /* Component a1. */ /* Setting parameters for component a1. */ SIG_MESSAGE("a1 (Init:SetPar)"); SIG_MESSAGE("a1 (Init:Place/Rotate)"); rot_set_rotation(mcrotaa1, (0.0)*DEG2RAD, (0.0)*DEG2RAD, (0.0)*DEG2RAD); #line 9528 "tof_diffraction.c" rot_copy(mcrotra1, mcrotaa1); mcposaa1 = coords_set( #line 21 "tof_diffraction.instr" 0, #line 21 "tof_diffraction.instr" 0, #line 21 "tof_diffraction.instr" 0); #line 9537 "tof_diffraction.c" mctc1 = coords_neg(mcposaa1); mcposra1 = rot_apply(mcrotaa1, mctc1); mcDEBUG_COMPONENT("a1", mcposaa1, mcrotaa1) mccomp_posa[1] = mcposaa1; mccomp_posr[1] = mcposra1; mcNCounter[1] = mcPCounter[1] = mcP2Counter[1] = 0; mcAbsorbProp[1]= 0; /* Component moderator. */ /* Setting parameters for component moderator. */ SIG_MESSAGE("moderator (Init:SetPar)"); #line 25 "tof_diffraction.instr" mccmoderator_Emin = - mciplambda1; #line 25 "tof_diffraction.instr" mccmoderator_Emax = - mciplambda2; #line 25 "tof_diffraction.instr" mccmoderator_dist = 4.0; #line 26 "tof_diffraction.instr" mccmoderator_focus_xw = 0.001; #line 26 "tof_diffraction.instr" mccmoderator_focus_yh = 0.001; #line 26 "tof_diffraction.instr" mccmoderator_xwidth = 0.001; #line 26 "tof_diffraction.instr" mccmoderator_yheight = 0.001; #line 27 "tof_diffraction.instr" mccmoderator_CAngle = 0.0; #line 27 "tof_diffraction.instr" mccmoderator_SAC = 1; #line 58 "tof_diffraction.instr" mccmoderator_Lmin = 0; #line 58 "tof_diffraction.instr" mccmoderator_Lmax = 0; #line 58 "tof_diffraction.instr" mccmoderator_target_index = + 1; #line 58 "tof_diffraction.instr" mccmoderator_verbose = 0; #line 9574 "tof_diffraction.c" SIG_MESSAGE("moderator (Init:Place/Rotate)"); rot_set_rotation(mctr1, (0.0)*DEG2RAD, (0.0)*DEG2RAD, (0.0)*DEG2RAD); #line 9581 "tof_diffraction.c" rot_mul(mctr1, mcrotaa1, mcrotamoderator); rot_transpose(mcrotaa1, mctr1); rot_mul(mcrotamoderator, mctr1, mcrotrmoderator); mctc1 = coords_set( #line 28 "tof_diffraction.instr" 0.0, #line 28 "tof_diffraction.instr" 0.0, #line 28 "tof_diffraction.instr" 0.0); #line 9592 "tof_diffraction.c" rot_transpose(mcrotaa1, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposamoderator = coords_add(mcposaa1, mctc2); mctc1 = coords_sub(mcposaa1, mcposamoderator); mcposrmoderator = rot_apply(mcrotamoderator, mctc1); mcDEBUG_COMPONENT("moderator", mcposamoderator, mcrotamoderator) mccomp_posa[2] = mcposamoderator; mccomp_posr[2] = mcposrmoderator; mcNCounter[2] = mcPCounter[2] = mcP2Counter[2] = 0; mcAbsorbProp[2]= 0; /* Component pinhole. */ /* Setting parameters for component pinhole. */ SIG_MESSAGE("pinhole (Init:SetPar)"); #line 43 "tof_diffraction.instr" mccpinhole_xmin = -0.01; #line 43 "tof_diffraction.instr" mccpinhole_xmax = 0.01; #line 43 "tof_diffraction.instr" mccpinhole_ymin = -0.01; #line 43 "tof_diffraction.instr" mccpinhole_ymax = 0.01; #line 43 "tof_diffraction.instr" mccpinhole_radius = 0; #line 32 "tof_diffraction.instr" mccpinhole_xwidth = 0.002; #line 33 "tof_diffraction.instr" mccpinhole_yheight = 0.002; #line 9620 "tof_diffraction.c" SIG_MESSAGE("pinhole (Init:Place/Rotate)"); rot_set_rotation(mctr1, (0.0)*DEG2RAD, (0.0)*DEG2RAD, (0.0)*DEG2RAD); #line 9627 "tof_diffraction.c" rot_mul(mctr1, mcrotamoderator, mcrotapinhole); rot_transpose(mcrotamoderator, mctr1); rot_mul(mcrotapinhole, mctr1, mcrotrpinhole); mctc1 = coords_set( #line 34 "tof_diffraction.instr" 0.0, #line 34 "tof_diffraction.instr" 0.0, #line 34 "tof_diffraction.instr" mcipmoderator_pinhole_distance); #line 9638 "tof_diffraction.c" rot_transpose(mcrotamoderator, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposapinhole = coords_add(mcposamoderator, mctc2); mctc1 = coords_sub(mcposamoderator, mcposapinhole); mcposrpinhole = rot_apply(mcrotapinhole, mctc1); mcDEBUG_COMPONENT("pinhole", mcposapinhole, mcrotapinhole) mccomp_posa[3] = mcposapinhole; mccomp_posr[3] = mcposrpinhole; mcNCounter[3] = mcPCounter[3] = mcP2Counter[3] = 0; mcAbsorbProp[3]= 0; /* Component sample1. */ /* Setting parameters for component sample1. */ SIG_MESSAGE("sample1 (Init:SetPar)"); #line 128 "tof_diffraction.instr" mccsample1_xwidth = 0; #line 39 "tof_diffraction.instr" mccsample1_yheight = 0.005; #line 128 "tof_diffraction.instr" mccsample1_zthick = 0; #line 41 "tof_diffraction.instr" mccsample1_radius = 0.0025; #line 128 "tof_diffraction.instr" mccsample1_thickness = 0; #line 128 "tof_diffraction.instr" if(0) strncpy(mccsample1_geometry, 0 ? 0 : "", 16384); else mccsample1_geometry[0]='\0'; #line 42 "tof_diffraction.instr" if(mcipsample_file) strncpy(mccsample1_nxsFileName, mcipsample_file ? mcipsample_file : "", 16384); else mccsample1_nxsFileName[0]='\0'; #line 43 "tof_diffraction.instr" mccsample1_max_hkl = 8; #line 47 "tof_diffraction.instr" mccsample1_d_phi = 110.0; #line 128 "tof_diffraction.instr" if("") strncpy(mccsample1_strainFileName, "" ? "" : "", 16384); else mccsample1_strainFileName[0]='\0'; #line 128 "tof_diffraction.instr" mccsample1_sample_temp = 293.0; #line 9674 "tof_diffraction.c" SIG_MESSAGE("sample1 (Init:Place/Rotate)"); rot_set_rotation(mcrotasample1, #line 48 "tof_diffraction.instr" (0)*DEG2RAD, #line 48 "tof_diffraction.instr" (0)*DEG2RAD, #line 48 "tof_diffraction.instr" (0)*DEG2RAD); #line 9684 "tof_diffraction.c" rot_transpose(mcrotapinhole, mctr1); rot_mul(mcrotasample1, mctr1, mcrotrsample1); mctc1 = coords_set( #line 48 "tof_diffraction.instr" mcipsample_x, #line 48 "tof_diffraction.instr" 0.0, #line 48 "tof_diffraction.instr" mcippinhole_sample_distance); #line 9694 "tof_diffraction.c" rot_transpose(mcrotapinhole, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposasample1 = coords_add(mcposapinhole, mctc2); mctc1 = coords_sub(mcposapinhole, mcposasample1); mcposrsample1 = rot_apply(mcrotasample1, mctc1); mcDEBUG_COMPONENT("sample1", mcposasample1, mcrotasample1) mccomp_posa[4] = mcposasample1; mccomp_posr[4] = mcposrsample1; mcNCounter[4] = mcPCounter[4] = mcP2Counter[4] = 0; mcAbsorbProp[4]= 0; /* Component sample. */ /* Setting parameters for component sample. */ SIG_MESSAGE("sample (Init:SetPar)"); SIG_MESSAGE("sample (Init:Place/Rotate)"); rot_set_rotation(mctr1, #line 51 "tof_diffraction.instr" (0)*DEG2RAD, #line 51 "tof_diffraction.instr" (0)*DEG2RAD, #line 51 "tof_diffraction.instr" (0)*DEG2RAD); #line 9717 "tof_diffraction.c" rot_mul(mctr1, mcrotasample1, mcrotasample); rot_transpose(mcrotasample1, mctr1); rot_mul(mcrotasample, mctr1, mcrotrsample); mctc1 = coords_set( #line 51 "tof_diffraction.instr" 0, #line 51 "tof_diffraction.instr" 0, #line 51 "tof_diffraction.instr" 0); #line 9728 "tof_diffraction.c" rot_transpose(mcrotasample1, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposasample = coords_add(mcposasample1, mctc2); mctc1 = coords_sub(mcposasample1, mcposasample); mcposrsample = rot_apply(mcrotasample, mctc1); mcDEBUG_COMPONENT("sample", mcposasample, mcrotasample) mccomp_posa[5] = mcposasample; mccomp_posr[5] = mcposrsample; mcNCounter[5] = mcPCounter[5] = mcP2Counter[5] = 0; mcAbsorbProp[5]= 0; /* Component beamstop. */ /* Setting parameters for component beamstop. */ SIG_MESSAGE("beamstop (Init:SetPar)"); #line 44 "tof_diffraction.instr" mccbeamstop_xmin = -0.05; #line 44 "tof_diffraction.instr" mccbeamstop_xmax = 0.05; #line 44 "tof_diffraction.instr" mccbeamstop_ymin = -0.05; #line 44 "tof_diffraction.instr" mccbeamstop_ymax = 0.05; #line 45 "tof_diffraction.instr" mccbeamstop_xwidth = 0; #line 45 "tof_diffraction.instr" mccbeamstop_yheight = 0; #line 54 "tof_diffraction.instr" mccbeamstop_radius = 0.005; #line 9756 "tof_diffraction.c" SIG_MESSAGE("beamstop (Init:Place/Rotate)"); rot_set_rotation(mctr1, (0.0)*DEG2RAD, (0.0)*DEG2RAD, (0.0)*DEG2RAD); #line 9763 "tof_diffraction.c" rot_mul(mctr1, mcrotasample, mcrotabeamstop); rot_transpose(mcrotasample, mctr1); rot_mul(mcrotabeamstop, mctr1, mcrotrbeamstop); mctc1 = coords_set( #line 55 "tof_diffraction.instr" - mcipsample_x, #line 55 "tof_diffraction.instr" 0, #line 55 "tof_diffraction.instr" 0.05); #line 9774 "tof_diffraction.c" rot_transpose(mcrotasample, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposabeamstop = coords_add(mcposasample, mctc2); mctc1 = coords_sub(mcposasample, mcposabeamstop); mcposrbeamstop = rot_apply(mcrotabeamstop, mctc1); mcDEBUG_COMPONENT("beamstop", mcposabeamstop, mcrotabeamstop) mccomp_posa[6] = mcposabeamstop; mccomp_posr[6] = mcposrbeamstop; mcNCounter[6] = mcPCounter[6] = mcP2Counter[6] = 0; mcAbsorbProp[6]= 0; /* Component tofmon. */ /* Setting parameters for component tofmon. */ SIG_MESSAGE("tofmon (Init:SetPar)"); #line 62 "tof_diffraction.instr" if("tofmon.dat") strncpy(mcctofmon_filename, "tofmon.dat" ? "tofmon.dat" : "", 16384); else mcctofmon_filename[0]='\0'; #line 46 "tof_diffraction.instr" mcctofmon_xmin = -0.05; #line 46 "tof_diffraction.instr" mcctofmon_xmax = 0.05; #line 46 "tof_diffraction.instr" mcctofmon_ymin = -0.05; #line 46 "tof_diffraction.instr" mcctofmon_ymax = 0.05; #line 63 "tof_diffraction.instr" mcctofmon_xwidth = 0.1; #line 64 "tof_diffraction.instr" mcctofmon_yheight = 0.1; #line 65 "tof_diffraction.instr" mcctofmon_tmin = 25000; #line 66 "tof_diffraction.instr" mcctofmon_tmax = 45000; #line 47 "tof_diffraction.instr" mcctofmon_dt = 1.0; #line 67 "tof_diffraction.instr" mcctofmon_restore_neutron = 1; #line 9810 "tof_diffraction.c" SIG_MESSAGE("tofmon (Init:Place/Rotate)"); rot_set_rotation(mctr1, (0.0)*DEG2RAD, (0.0)*DEG2RAD, (0.0)*DEG2RAD); #line 9817 "tof_diffraction.c" rot_mul(mctr1, mcrotasample, mcrotatofmon); rot_transpose(mcrotabeamstop, mctr1); rot_mul(mcrotatofmon, mctr1, mcrotrtofmon); mctc1 = coords_set( #line 68 "tof_diffraction.instr" - mcipsample_x, #line 68 "tof_diffraction.instr" 0, #line 68 "tof_diffraction.instr" mcipsample_detector_distance); #line 9828 "tof_diffraction.c" rot_transpose(mcrotasample, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposatofmon = coords_add(mcposasample, mctc2); mctc1 = coords_sub(mcposabeamstop, mcposatofmon); mcposrtofmon = rot_apply(mcrotatofmon, mctc1); mcDEBUG_COMPONENT("tofmon", mcposatofmon, mcrotatofmon) mccomp_posa[7] = mcposatofmon; mccomp_posr[7] = mcposrtofmon; mcNCounter[7] = mcPCounter[7] = mcP2Counter[7] = 0; mcAbsorbProp[7]= 0; /* Component lmon. */ /* Setting parameters for component lmon. */ SIG_MESSAGE("lmon (Init:SetPar)"); #line 73 "tof_diffraction.instr" if("lmon.dat") strncpy(mcclmon_filename, "lmon.dat" ? "lmon.dat" : "", 16384); else mcclmon_filename[0]='\0'; #line 49 "tof_diffraction.instr" mcclmon_xmin = -0.05; #line 49 "tof_diffraction.instr" mcclmon_xmax = 0.05; #line 49 "tof_diffraction.instr" mcclmon_ymin = -0.05; #line 49 "tof_diffraction.instr" mcclmon_ymax = 0.05; #line 74 "tof_diffraction.instr" mcclmon_xwidth = 0.1; #line 75 "tof_diffraction.instr" mcclmon_yheight = 0.1; #line 76 "tof_diffraction.instr" mcclmon_Lmin = mciplambda1 - mciplambda2; #line 77 "tof_diffraction.instr" mcclmon_Lmax = mciplambda1 + mciplambda2; #line 78 "tof_diffraction.instr" mcclmon_restore_neutron = 1; #line 9862 "tof_diffraction.c" SIG_MESSAGE("lmon (Init:Place/Rotate)"); rot_set_rotation(mctr1, (0.0)*DEG2RAD, (0.0)*DEG2RAD, (0.0)*DEG2RAD); #line 9869 "tof_diffraction.c" rot_mul(mctr1, mcrotasample, mcrotalmon); rot_transpose(mcrotatofmon, mctr1); rot_mul(mcrotalmon, mctr1, mcrotrlmon); mctc1 = coords_set( #line 79 "tof_diffraction.instr" - mcipsample_x, #line 79 "tof_diffraction.instr" 0, #line 79 "tof_diffraction.instr" mcipsample_detector_distance); #line 9880 "tof_diffraction.c" rot_transpose(mcrotasample, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposalmon = coords_add(mcposasample, mctc2); mctc1 = coords_sub(mcposatofmon, mcposalmon); mcposrlmon = rot_apply(mcrotalmon, mctc1); mcDEBUG_COMPONENT("lmon", mcposalmon, mcrotalmon) mccomp_posa[8] = mcposalmon; mccomp_posr[8] = mcposrlmon; mcNCounter[8] = mcPCounter[8] = mcP2Counter[8] = 0; mcAbsorbProp[8]= 0; /* Component rot90. */ /* Setting parameters for component rot90. */ SIG_MESSAGE("rot90 (Init:SetPar)"); SIG_MESSAGE("rot90 (Init:Place/Rotate)"); rot_set_rotation(mctr1, #line 82 "tof_diffraction.instr" (0)*DEG2RAD, #line 82 "tof_diffraction.instr" (60)*DEG2RAD, #line 82 "tof_diffraction.instr" (0)*DEG2RAD); #line 9903 "tof_diffraction.c" rot_mul(mctr1, mcrotasample, mcrotarot90); rot_transpose(mcrotalmon, mctr1); rot_mul(mcrotarot90, mctr1, mcrotrrot90); mctc1 = coords_set( #line 82 "tof_diffraction.instr" 0, #line 82 "tof_diffraction.instr" 0, #line 82 "tof_diffraction.instr" 0); #line 9914 "tof_diffraction.c" rot_transpose(mcrotasample, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposarot90 = coords_add(mcposasample, mctc2); mctc1 = coords_sub(mcposalmon, mcposarot90); mcposrrot90 = rot_apply(mcrotarot90, mctc1); mcDEBUG_COMPONENT("rot90", mcposarot90, mcrotarot90) mccomp_posa[9] = mcposarot90; mccomp_posr[9] = mcposrrot90; mcNCounter[9] = mcPCounter[9] = mcP2Counter[9] = 0; mcAbsorbProp[9]= 0; /* Component blende. */ /* Setting parameters for component blende. */ SIG_MESSAGE("blende (Init:SetPar)"); #line 43 "tof_diffraction.instr" mccblende_xmin = -0.01; #line 43 "tof_diffraction.instr" mccblende_xmax = 0.01; #line 43 "tof_diffraction.instr" mccblende_ymin = -0.01; #line 43 "tof_diffraction.instr" mccblende_ymax = 0.01; #line 43 "tof_diffraction.instr" mccblende_radius = 0; #line 88 "tof_diffraction.instr" mccblende_xwidth = 0.001; #line 89 "tof_diffraction.instr" mccblende_yheight = 0.1002; #line 9942 "tof_diffraction.c" SIG_MESSAGE("blende (Init:Place/Rotate)"); rot_set_rotation(mctr1, (0.0)*DEG2RAD, (0.0)*DEG2RAD, (0.0)*DEG2RAD); #line 9949 "tof_diffraction.c" rot_mul(mctr1, mcrotarot90, mcrotablende); rot_transpose(mcrotarot90, mctr1); rot_mul(mcrotablende, mctr1, mcrotrblende); mctc1 = coords_set( #line 90 "tof_diffraction.instr" 0.0, #line 90 "tof_diffraction.instr" 0.0, #line 90 "tof_diffraction.instr" 0.026); #line 9960 "tof_diffraction.c" rot_transpose(mcrotarot90, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposablende = coords_add(mcposarot90, mctc2); mctc1 = coords_sub(mcposarot90, mcposablende); mcposrblende = rot_apply(mcrotablende, mctc1); mcDEBUG_COMPONENT("blende", mcposablende, mcrotablende) mccomp_posa[10] = mcposablende; mccomp_posr[10] = mcposrblende; mcNCounter[10] = mcPCounter[10] = mcP2Counter[10] = 0; mcAbsorbProp[10]= 0; /* Component detector. */ /* Setting parameters for component detector. */ SIG_MESSAGE("detector (Init:SetPar)"); #line 93 "tof_diffraction.instr" if("PSD.dat") strncpy(mccdetector_filename, "PSD.dat" ? "PSD.dat" : "", 16384); else mccdetector_filename[0]='\0'; #line 93 "tof_diffraction.instr" mccdetector_xmin = -0.5; #line 94 "tof_diffraction.instr" mccdetector_xmax = 0.5; #line 94 "tof_diffraction.instr" mccdetector_ymin = -0.3; #line 94 "tof_diffraction.instr" mccdetector_ymax = 0.3; #line 49 "tof_diffraction.instr" mccdetector_xwidth = 0; #line 49 "tof_diffraction.instr" mccdetector_yheight = 0; #line 49 "tof_diffraction.instr" mccdetector_restore_neutron = 0; #line 9990 "tof_diffraction.c" SIG_MESSAGE("detector (Init:Place/Rotate)"); rot_set_rotation(mctr1, (0.0)*DEG2RAD, (0.0)*DEG2RAD, (0.0)*DEG2RAD); #line 9997 "tof_diffraction.c" rot_mul(mctr1, mcrotarot90, mcrotadetector); rot_transpose(mcrotablende, mctr1); rot_mul(mcrotadetector, mctr1, mcrotrdetector); mctc1 = coords_set( #line 95 "tof_diffraction.instr" 0, #line 95 "tof_diffraction.instr" 0, #line 95 "tof_diffraction.instr" 1.0); #line 10008 "tof_diffraction.c" rot_transpose(mcrotarot90, mctr1); mctc2 = rot_apply(mctr1, mctc1); mcposadetector = coords_add(mcposarot90, mctc2); mctc1 = coords_sub(mcposablende, mcposadetector); mcposrdetector = rot_apply(mcrotadetector, mctc1); mcDEBUG_COMPONENT("detector", mcposadetector, mcrotadetector) mccomp_posa[11] = mcposadetector; mccomp_posr[11] = mcposrdetector; mcNCounter[11] = mcPCounter[11] = mcP2Counter[11] = 0; mcAbsorbProp[11]= 0; /* Component initializations. */ /* Initializations for component a1. */ SIG_MESSAGE("a1 (Init)"); /* Initializations for component moderator. */ SIG_MESSAGE("moderator (Init)"); #define mccompcurname moderator #define mccompcurtype ISIS_moderator #define mccompcurindex 2 #define Face mccmoderator_Face #define p_in mccmoderator_p_in #define Tnpts mccmoderator_Tnpts #define scaleSize mccmoderator_scaleSize #define angleArea mccmoderator_angleArea #define Nsim mccmoderator_Nsim #define Ncount mccmoderator_Ncount #define TS mccmoderator_TS #define rtE0 mccmoderator_rtE0 #define rtE1 mccmoderator_rtE1 #define rtmodX mccmoderator_rtmodX #define rtmodY mccmoderator_rtmodY #define TargetStation mccmoderator_TargetStation #define CurrentWeight mccmoderator_CurrentWeight #define Emin mccmoderator_Emin #define Emax mccmoderator_Emax #define dist mccmoderator_dist #define focus_xw mccmoderator_focus_xw #define focus_yh mccmoderator_focus_yh #define xwidth mccmoderator_xwidth #define yheight mccmoderator_yheight #define CAngle mccmoderator_CAngle #define SAC mccmoderator_SAC #define Lmin mccmoderator_Lmin #define Lmax mccmoderator_Lmax #define target_index mccmoderator_target_index #define verbose mccmoderator_verbose #line 836 "/mnt/lustre/apps/centos73/mcstas/2.4.1/contrib/ISIS_moderator.comp" { /* READ IN THE ENERGY FILE */ char fname[256]; /* Variables */ FILE* TFile; double tmp; char lowerFace[255]; int Bcnt; int i; struct BeamLine { char Name[50]; double Xsize; double Ysize; } Olist[50]; if (target_index && !dist) { Coords ToTarget; double tx,ty,tz; ToTarget = coords_sub(POS_A_COMP_INDEX(INDEX_CURRENT_COMP+target_index),POS_A_CURRENT_COMP); ToTarget = rot_apply(ROT_A_CURRENT_COMP, ToTarget); coords_get(ToTarget, &tx, &ty, &tz); dist=sqrt(tx*tx+ty*ty+tz*tz); } Nsim=(double)mcget_ncount(); Bcnt=0; // CH4 face 1 (north) strcpy(Olist[Bcnt].Name,"mari"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"gem"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"hrpd"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"pearl"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; // CH4 face 2 (south) strcpy(Olist[Bcnt].Name,"sandals"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"prisma"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; // H2 face strcpy(Olist[Bcnt].Name,"surf"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; strcpy(Olist[Bcnt].Name,"crisp"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; strcpy(Olist[Bcnt].Name,"iris"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; // Water face 1 strcpy(Olist[Bcnt].Name,"polaris"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"het"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"tosca"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; // Water face 2 strcpy(Olist[Bcnt].Name,"maps"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"evs"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"sxd"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; // TS1 Generics strcpy(Olist[Bcnt].Name,"ch4"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; strcpy(Olist[Bcnt].Name,"h2"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; strcpy(Olist[Bcnt].Name,"water"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.115; Bcnt++; // TS2 Generics strcpy(Olist[Bcnt].Name,"groove"); Olist[Bcnt].Xsize=0.08333; Olist[Bcnt].Ysize=0.03; Bcnt++; strcpy(Olist[Bcnt].Name,"hydrogen"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; strcpy(Olist[Bcnt].Name,"narrow"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; strcpy(Olist[Bcnt].Name,"broad"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; // TS2 groove strcpy(Olist[Bcnt].Name,"e1"); Olist[Bcnt].Xsize=0.08333; Olist[Bcnt].Ysize=0.03; Bcnt++; strcpy(Olist[Bcnt].Name,"e2"); Olist[Bcnt].Xsize=0.08333; Olist[Bcnt].Ysize=0.03; Bcnt++; strcpy(Olist[Bcnt].Name,"e3"); Olist[Bcnt].Xsize=0.08333; Olist[Bcnt].Ysize=0.03; Bcnt++; strcpy(Olist[Bcnt].Name,"e4"); Olist[Bcnt].Xsize=0.08333; Olist[Bcnt].Ysize=0.03; Bcnt++; strcpy(Olist[Bcnt].Name,"e5"); Olist[Bcnt].Xsize=0.08333; Olist[Bcnt].Ysize=0.03; Bcnt++; //Broad face strcpy(Olist[Bcnt].Name,"e6"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; strcpy(Olist[Bcnt].Name,"e7"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; strcpy(Olist[Bcnt].Name,"e8"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; strcpy(Olist[Bcnt].Name,"e9"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; // Narrow face strcpy(Olist[Bcnt].Name,"w1"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; strcpy(Olist[Bcnt].Name,"w2"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; strcpy(Olist[Bcnt].Name,"w3"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; strcpy(Olist[Bcnt].Name,"w4"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.12; Bcnt++; //Hydrogen face strcpy(Olist[Bcnt].Name,"w5"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; strcpy(Olist[Bcnt].Name,"w6"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; strcpy(Olist[Bcnt].Name,"w7"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; strcpy(Olist[Bcnt].Name,"w8"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; strcpy(Olist[Bcnt].Name,"w9"); Olist[Bcnt].Xsize=0.12; Olist[Bcnt].Ysize=0.11; Bcnt++; /* write out version number */ fprintf(stderr,"**********************************************************************\n"); fprintf(stderr,"**** This is ISIS_moderator.comp version 2.0 (25/8/05) ****\n"); fprintf(stderr,"**** Please check to see if your files are up-to-date ****\n"); fprintf(stderr,"**** http://www.isis.rl.ac.uk/Computing/Software/MC/index.htm ****\n"); fprintf(stderr,"**********************************************************************\n\n"); /* convert arguments to runtime variables so that they may be altered */ rtE0=Emin; rtE1=Emax; rtmodX=xwidth; rtmodY=yheight; /* Convert NEGATIVE energy (denoting angstroms) into meV */ if ( (rtE0<0 && Emax>0) | (rtE0>0 && Emax<0)) { fprintf(stderr,"Cannot have differing signs for Emin and Emax, choose Angstroms or meV!\n"); exit(1); } if (rtE0<0 && Emax<0) { fprintf (stderr,"converting Angstroms to meV\n"); rtE0=81.793936/(rtE0*rtE0); rtE1=81.793936/(rtE1*rtE1); } if (Lmin && Lmax) { fprintf (stderr,"converting Angstroms to meV\n"); rtE0=81.793936/(Lmin*Lmin); rtE1=81.793936/(Lmax*Lmax); } if (rtE0>rtE1) { tmp=rtE1; rtE1=rtE0; rtE0=tmp; fprintf (stderr,"%g A -> %g A => %g meV -> %g meV\n",-Emin,-Emax,rtE0,rtE1); } /**********************************************************************/ Tnpts=0; Ncount=0; fprintf(stderr,"Face == %s \n",Face); for(i=0;Face[i] && Face[i]!=' ';i++) lowerFace[i]=tolower(Face[i]); lowerFace[i]=0; for(i=0;i \n"); for(i=0;i0.0) ? strArea(dist, rtmodX, rtmodY, focus_xw, focus_yh) : 2*3.141592654; else angleArea=1.0; /* TS1: MCNPX runs were done for 60 mu-A, but the source runs at 160 mu-A, 40 Hz. TS2: MCNPX runs were done for 60 mu-A, but the source runs at 40-mu-A, 10 Hz. */ if (TargetStation == 1) { CurrentWeight = 160.0/60.0; } else { CurrentWeight = 40.0/60.0; } } #line 10278 "tof_diffraction.c" #undef verbose #undef target_index #undef Lmax #undef Lmin #undef SAC #undef CAngle #undef yheight #undef xwidth #undef focus_yh #undef focus_xw #undef dist #undef Emax #undef Emin #undef CurrentWeight #undef TargetStation #undef rtmodY #undef rtmodX #undef rtE1 #undef rtE0 #undef TS #undef Ncount #undef Nsim #undef angleArea #undef scaleSize #undef Tnpts #undef p_in #undef Face #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Initializations for component pinhole. */ SIG_MESSAGE("pinhole (Init)"); #define mccompcurname pinhole #define mccompcurtype Slit #define mccompcurindex 3 #define xmin mccpinhole_xmin #define xmax mccpinhole_xmax #define ymin mccpinhole_ymin #define ymax mccpinhole_ymax #define radius mccpinhole_radius #define xwidth mccpinhole_xwidth #define yheight mccpinhole_yheight #line 47 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Slit.comp" { if (xwidth > 0) { xmax=xwidth/2; xmin=-xmax; } if (yheight > 0) { ymax=yheight/2; ymin=-ymax; } if (xmin == 0 && xmax == 0 && ymin == 0 && ymax == 0 && radius == 0) { fprintf(stderr,"Slit: %s: Error: give geometry\n", NAME_CURRENT_COMP); exit(-1); } } #line 10330 "tof_diffraction.c" #undef yheight #undef xwidth #undef radius #undef ymax #undef ymin #undef xmax #undef xmin #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Initializations for component sample1. */ SIG_MESSAGE("sample1 (Init)"); #define mccompcurname sample1 #define mccompcurtype sample_nxs #define mccompcurindex 4 #define TransOnly mccsample1_TransOnly #define IncohScat mccsample1_IncohScat #define MultiScat mccsample1_MultiScat #define isrect mccsample1_isrect #define intersect mccsample1_intersect #define nxs_init_success mccsample1_nxs_init_success #define p_transmit mccsample1_p_transmit #define xsect_total mccsample1_xsect_total #define xsect_coherent mccsample1_xsect_coherent #define xsect_incoherent mccsample1_xsect_incoherent #define xsect_absorption mccsample1_xsect_absorption #define lambda mccsample1_lambda #define velocity mccsample1_velocity #define fullpath mccsample1_fullpath #define t1 mccsample1_t1 #define t2 mccsample1_t2 #define uc mccsample1_uc #define A mccsample1_A #define mu_factor mccsample1_mu_factor #define sd mccsample1_sd #define V2L mccsample1_V2L #define xwidth mccsample1_xwidth #define yheight mccsample1_yheight #define zthick mccsample1_zthick #define radius mccsample1_radius #define thickness mccsample1_thickness #define geometry mccsample1_geometry #define nxsFileName mccsample1_nxsFileName #define max_hkl mccsample1_max_hkl #define d_phi mccsample1_d_phi #define strainFileName mccsample1_strainFileName #define sample_temp mccsample1_sample_temp #line 345 "sample_nxs.comp" { fprintf(stderr, "%s: Using libnxs version %s\n", NAME_CURRENT_COMP, nxs_version()); shape = -1; /* -1:no shape, 0:cyl, 1:box, 2:sphere, 3:any-shape */ if( geometry && strlen(geometry) && strcmp(geometry, "NULL") && strcmp(geometry, "0") ) { if( off_init(geometry, xwidth, yheight, zthick, 0, &offdata) ) { shape = 3; /* arbitrary */ thickness=0; //concentric=0; } } else if( xwidth && yheight && zthick ) shape = 1; /* box */ else if (radius > 0 && yheight) shape = 0; /* cylinder */ else if (radius > 0 && !yheight) shape = 2; /* sphere */ if( shape < 0 ) exit( fprintf(stderr,"Sample_nxs %s has invalid dimensions.\n" "ERROR: Please check parameter values (xwidth, yheight, zthick, radius).\n", NAME_CURRENT_COMP) ); if( readStrainFile( strainFileName, &sd ) ) { fprintf(stderr, "%s: No strain data found! Recalculation of d-values not used.\n", NAME_CURRENT_COMP); sd.n_entries = 0; } if (TransOnly) { fprintf(stderr, "%s: Performing neutron transmission only (no scattering).\n", NAME_CURRENT_COMP); if( sd.n_entries>0 ) fprintf(stderr, "%s: WARNING: Cannot use strain data in TransOnly mode!\n", NAME_CURRENT_COMP); } else { if (IncohScat) fprintf(stderr, "%s: Enabling incoherent scattering.\n", NAME_CURRENT_COMP); if (MultiScat) { fprintf(stderr, "%s: Enabling multiple scattering.\n", NAME_CURRENT_COMP); if (d_phi) { fprintf(stderr, "%s: WARNING: No focussing possible in multiple scattering mode. Setting d_phi=0.\n", NAME_CURRENT_COMP); d_phi = 0; } } } /* read unit cell parameters from file and initialise hkl */ uc = nxs_newUnitCell(); NXS_AtomInfo *atomInfoList; int numAtoms = nxs_readParameterFile( nxsFileName, &uc, &atomInfoList); if( numAtoms < 1 ) { /* fallback solution: if no file exists, use alpha_iron */ fprintf(stderr, "%s: WARNING: nxs parameter file %s NOT found! Using default values...\n", NAME_CURRENT_COMP, nxsFileName); strncpy(uc.spaceGroup,"229",MAX_CHARS_SPACEGROUP); uc.a = 2.866; uc.alpha = 90.0; uc.debyeTemp = 464.0; NXS_AtomInfo ai; strncpy(ai.label,"Fe",MAX_CHARS_ATOMLABEL); ai.b_coherent = 9.45; ai.sigmaIncoherent = 0.4; ai.sigmaAbsorption = 2.56; ai.molarMass = 55.85; ai.x[0] = ai.y[0] = ai.z[0] = 0.0; atomInfoList = (NXS_AtomInfo*)realloc( atomInfoList, sizeof(NXS_AtomInfo) ); atomInfoList[0] = ai; numAtoms = 1; } unsigned int i; if( NXS_ERROR_OK != nxs_initUnitCell(&uc) ) { fprintf(stderr, "%s: WARNING: No nxs parameters set! Sample will be transparent!\n", NAME_CURRENT_COMP); nxs_init_success = 0; } else { nxs_init_success = 1; uc.temperature = sample_temp; for( i=0; i0 ) { if( sd.d0_hoop<=1E-6 ) sd.d0_hoop = uc.a; if( sd.d0_radial<=1E-6 ) sd.d0_radial = uc.a; if( sd.d0_axial<=1E-6 ) sd.d0_axial = uc.a; } V2L = 2.0 * PI / V2K; } } #line 10480 "tof_diffraction.c" #undef sample_temp #undef strainFileName #undef d_phi #undef max_hkl #undef nxsFileName #undef geometry #undef thickness #undef radius #undef zthick #undef yheight #undef xwidth #undef V2L #undef sd #undef mu_factor #undef A #undef uc #undef t2 #undef t1 #undef fullpath #undef velocity #undef lambda #undef xsect_absorption #undef xsect_incoherent #undef xsect_coherent #undef xsect_total #undef p_transmit #undef nxs_init_success #undef intersect #undef isrect #undef MultiScat #undef IncohScat #undef TransOnly #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Initializations for component sample. */ SIG_MESSAGE("sample (Init)"); /* Initializations for component beamstop. */ SIG_MESSAGE("beamstop (Init)"); #define mccompcurname beamstop #define mccompcurtype Beamstop #define mccompcurindex 6 #define xmin mccbeamstop_xmin #define xmax mccbeamstop_xmax #define ymin mccbeamstop_ymin #define ymax mccbeamstop_ymax #define xwidth mccbeamstop_xwidth #define yheight mccbeamstop_yheight #define radius mccbeamstop_radius #line 50 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Beamstop.comp" { if (xwidth > 0) { xmax = xwidth/2; xmin = -xmax; } if (yheight > 0) { ymax = yheight/2; ymin = -ymax; } if (xmin == 0 && xmax == 0 && ymin == 0 & ymax == 0 && radius == 0) { fprintf(stderr,"Beamstop: %s: Error: give geometry\n", NAME_CURRENT_COMP); exit(-1); } } #line 10540 "tof_diffraction.c" #undef radius #undef yheight #undef xwidth #undef ymax #undef ymin #undef xmax #undef xmin #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Initializations for component tofmon. */ SIG_MESSAGE("tofmon (Init)"); #define mccompcurname tofmon #define mccompcurtype TOF_monitor #define mccompcurindex 7 #define nt mcctofmon_nt #define TOF_N mcctofmon_TOF_N #define TOF_p mcctofmon_TOF_p #define TOF_p2 mcctofmon_TOF_p2 #define t_min mcctofmon_t_min #define t_max mcctofmon_t_max #define delta_t mcctofmon_delta_t #define filename mcctofmon_filename #define xmin mcctofmon_xmin #define xmax mcctofmon_xmax #define ymin mcctofmon_ymin #define ymax mcctofmon_ymax #define xwidth mcctofmon_xwidth #define yheight mcctofmon_yheight #define tmin mcctofmon_tmin #define tmax mcctofmon_tmax #define dt mcctofmon_dt #define restore_neutron mcctofmon_restore_neutron #line 60 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/TOF_monitor.comp" { int i; if (xwidth > 0) { xmax = xwidth/2; xmin = -xmax; } if (yheight > 0) { ymax = yheight/2; ymin = -ymax; } if ((xmin >= xmax) || (ymin >= ymax)) { printf("TOF_monitor: %s: Null detection area !\n" "ERROR (xwidth,yheight,xmin,xmax,ymin,ymax). Exiting", NAME_CURRENT_COMP); exit(0); } for (i=0; i 0) { xmax = xwidth/2; xmin = -xmax; } if (yheight > 0) { ymax = yheight/2; ymin = -ymax; } if ((xmin >= xmax) || (ymin >= ymax)) { printf("L_monitor: %s: Null detection area !\n" "ERROR (xwidth,yheight,xmin,xmax,ymin,ymax). Exiting", NAME_CURRENT_COMP); exit(0); } for (i=0; i 0) { xmax=xwidth/2; xmin=-xmax; } if (yheight > 0) { ymax=yheight/2; ymin=-ymax; } if (xmin == 0 && xmax == 0 && ymin == 0 && ymax == 0 && radius == 0) { fprintf(stderr,"Slit: %s: Error: give geometry\n", NAME_CURRENT_COMP); exit(-1); } } #line 10713 "tof_diffraction.c" #undef yheight #undef xwidth #undef radius #undef ymax #undef ymin #undef xmax #undef xmin #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Initializations for component detector. */ SIG_MESSAGE("detector (Init)"); #define mccompcurname detector #define mccompcurtype PSD_monitor #define mccompcurindex 11 #define nx mccdetector_nx #define ny mccdetector_ny #define PSD_N mccdetector_PSD_N #define PSD_p mccdetector_PSD_p #define PSD_p2 mccdetector_PSD_p2 #define filename mccdetector_filename #define xmin mccdetector_xmin #define xmax mccdetector_xmax #define ymin mccdetector_ymin #define ymax mccdetector_ymax #define xwidth mccdetector_xwidth #define yheight mccdetector_yheight #define restore_neutron mccdetector_restore_neutron #line 60 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/PSD_monitor.comp" { int i,j; if (xwidth > 0) { xmax = xwidth/2; xmin = -xmax; } if (yheight > 0) { ymax = yheight/2; ymin = -ymax; } if ((xmin >= xmax) || (ymin >= ymax)) { printf("PSD_monitor: %s: Null detection area !\n" "ERROR (xwidth,yheight,xmin,xmax,ymin,ymax). Exiting", NAME_CURRENT_COMP); exit(0); } for (i=0; imax var in param space */ double Ival,Tval,Eval; double Ddist; /* Temp versions of dist */ Ncount++; p=p_in; p=1.0; /* forcing */ z=0; x = 0.5*rtmodX*randpm1(); /* Get point +/-0.5 * */ y = 0.5*rtmodY*randpm1(); xf = 0.5*focus_xw*randpm1(); /* Choose focusing position uniformly */ yf = 0.5*focus_yh*randpm1(); dx = xf-x; dy = yf-y; if (dist>0.0) { r = sqrt(dx*dx+dy*dy+dist*dist); /* Actual distance to point */ Ddist=dist; w_focus = (SAC) ? angleArea : scaleSize*(dist*dist)/(r*r); } else /* Assume that we have a window 1metre infront of the moderator */ /* with size area of detector and solid angle 1.0 */ { r=1.0; w_focus=scaleSize; Ddist=1.0; } getPoint(&Tval,&Eval,&rtE0,&rtE1, TS); //fprintf(stderr,"outside %g mev\n", TS.Total ); if(Eval>rtE1 || Eval %g %g %g %g \n",Ncount,Eval,Tval,TS.Total,Ival); t=Tval; p=w_focus*Ival*CurrentWeight/Nsim; } #line 11071 "tof_diffraction.c" } /* End of moderator=ISIS_moderator() SETTING parameter declarations. */ #undef CurrentWeight #undef TargetStation #undef rtmodY #undef rtmodX #undef rtE1 #undef rtE0 #undef TS #undef Ncount #undef Nsim #undef angleArea #undef scaleSize #undef Tnpts #undef p_in #undef Face #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Label for restoring neutron */ mcabsorbCompmoderator: if (RESTORE) /* restore if needed */ { RESTORE_NEUTRON(2, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); } #undef mcabsorbComp #undef p #undef sz #undef sy #undef sx #undef t #undef vz #undef vy #undef vx #undef z #undef y #undef x mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) /* TRACE Component pinhole [3] */ mccoordschange(mcposrpinhole, mcrotrpinhole, &mcnlx, &mcnly, &mcnlz, &mcnlvx, &mcnlvy, &mcnlvz, &mcnlsx, &mcnlsy, &mcnlsz); /* define label inside component pinhole (without coords transformations) */ mcJumpTrace_pinhole: SIG_MESSAGE("pinhole (Trace)"); mcDEBUG_COMP("pinhole") mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) #define x mcnlx #define y mcnly #define z mcnlz #define vx mcnlvx #define vy mcnlvy #define vz mcnlvz #define t mcnlt #define sx mcnlsx #define sy mcnlsy #define sz mcnlsz #define p mcnlp #define mcabsorbComp mcabsorbComppinhole STORE_NEUTRON(3, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); mcScattered=0; mcRestore=0; mcNCounter[3]++; mcPCounter[3] += p; mcP2Counter[3] += p*p; #define mccompcurname pinhole #define mccompcurtype Slit #define mccompcurindex 3 { /* Declarations of pinhole=Slit() SETTING parameters. */ MCNUM xmin = mccpinhole_xmin; MCNUM xmax = mccpinhole_xmax; MCNUM ymin = mccpinhole_ymin; MCNUM ymax = mccpinhole_ymax; MCNUM radius = mccpinhole_radius; MCNUM xwidth = mccpinhole_xwidth; MCNUM yheight = mccpinhole_yheight; #line 56 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Slit.comp" { PROP_Z0; if (((radius == 0) && (xxmax || yymax)) || ((radius != 0) && (x*x + y*y > radius*radius))) ABSORB; else SCATTER; } #line 11207 "tof_diffraction.c" } /* End of pinhole=Slit() SETTING parameter declarations. */ #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Label for restoring neutron */ mcabsorbComppinhole: if (RESTORE) /* restore if needed */ { RESTORE_NEUTRON(3, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); } #undef mcabsorbComp #undef p #undef sz #undef sy #undef sx #undef t #undef vz #undef vy #undef vx #undef z #undef y #undef x mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) /* TRACE Component sample1 [4] */ mccoordschange(mcposrsample1, mcrotrsample1, &mcnlx, &mcnly, &mcnlz, &mcnlvx, &mcnlvy, &mcnlvz, &mcnlsx, &mcnlsy, &mcnlsz); /* define label inside component sample1 (without coords transformations) */ mcJumpTrace_sample1: SIG_MESSAGE("sample1 (Trace)"); mcDEBUG_COMP("sample1") mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) #define x mcnlx #define y mcnly #define z mcnlz #define vx mcnlvx #define vy mcnlvy #define vz mcnlvz #define t mcnlt #define sx mcnlsx #define sy mcnlsy #define sz mcnlsz #define p mcnlp #define mcabsorbComp mcabsorbCompsample1 STORE_NEUTRON(4, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); mcScattered=0; mcRestore=0; mcNCounter[4]++; mcPCounter[4] += p; mcP2Counter[4] += p*p; #define mccompcurname sample1 #define mccompcurtype sample_nxs #define mccompcurindex 4 #define TransOnly mccsample1_TransOnly #define IncohScat mccsample1_IncohScat #define MultiScat mccsample1_MultiScat #define isrect mccsample1_isrect #define intersect mccsample1_intersect #define nxs_init_success mccsample1_nxs_init_success #define p_transmit mccsample1_p_transmit #define xsect_total mccsample1_xsect_total #define xsect_coherent mccsample1_xsect_coherent #define xsect_incoherent mccsample1_xsect_incoherent #define xsect_absorption mccsample1_xsect_absorption #define lambda mccsample1_lambda #define velocity mccsample1_velocity #define fullpath mccsample1_fullpath #define t1 mccsample1_t1 #define t2 mccsample1_t2 #define uc mccsample1_uc #define A mccsample1_A #define mu_factor mccsample1_mu_factor #define sd mccsample1_sd #define V2L mccsample1_V2L { /* Declarations of sample1=sample_nxs() SETTING parameters. */ MCNUM xwidth = mccsample1_xwidth; MCNUM yheight = mccsample1_yheight; MCNUM zthick = mccsample1_zthick; MCNUM radius = mccsample1_radius; MCNUM thickness = mccsample1_thickness; char* geometry = mccsample1_geometry; char* nxsFileName = mccsample1_nxsFileName; int max_hkl = mccsample1_max_hkl; MCNUM d_phi = mccsample1_d_phi; char* strainFileName = mccsample1_strainFileName; MCNUM sample_temp = mccsample1_sample_temp; #line 449 "sample_nxs.comp" { int i; double strain_axial; double strain_hoop; double strain_radial; int intersect = 0; double p_transmit; double lambda; double velocity; double fullpath; /* intersection times */ double t1; double t2; double xsect_total; /* box or cylinder? */ if ( shape == 0 ) intersect = cylinder_intersect(&t1,&t2,x,y,z,vx,vy,vz,radius, yheight); else if( shape == 1 ) intersect = box_intersect(&t1,&t2,x,y,z,vx,vy,vz,xwidth, yheight, zthick); //else if( shape == 2 ) // intersect = sphere_intersect(&t0, &t3, x, y, z, vx, vy, vz, radius); else if( shape == 3 ) intersect = off_intersect(&t1, &t2, NULL, NULL, x, y, z, vx, vy, vz, offdata ); /* neutron intersects? */ if( intersect && (t2>0) && nxs_init_success ) { /* get current velocity and wavelength */ velocity = sqrt( vx*vx + vy*vy + vz*vz ); lambda = V2L / velocity; xsect_coherent = nxs_CoherentElastic(lambda, &uc ); xsect_incoherent = nxs_IncoherentElastic(lambda, &uc ) + nxs_IncoherentInelastic(lambda, &uc ) + nxs_CoherentInelastic(lambda, &uc ); xsect_absorption = nxs_Absorption(lambda, &uc ); xsect_total = xsect_coherent + xsect_incoherent + xsect_absorption; /* Handle transmission only (imaging mode) */ if (TransOnly) { /* path through the sample */ fullpath = velocity * (t2-t1); /* change the neutron weight */ p_transmit = exp( -xsect_total * fullpath*1E2 / uc.volume ); p *= p_transmit; } /* ...also handle scattering events */ else { int ms_loop = 1; if( MultiScat ) ms_loop = 10; double path; while( ms_loop-- ) { /* go to an event point (randomly) */ path = rand01() * (t2-t1); PROP_DT( path + t1 ); // printf("%i: t1=%f t2=%f\n",ms_loop, t1*1000,t2*1000); path = path * velocity; /******** consider strain data... ********/ if( sd.n_entries>0) { /* take care of neutron position to find the correct (micro)strain value */ double pos = sqrt( x*x + z*z ); i = 0; while( pos>sd.pos_x[i] && sd.n_entries>i ) { i++; } if( i==0 ) { strain_hoop = sd.strains_hoop[i]; strain_radial = sd.strains_radial[i]; strain_axial = sd.strains_axial[i]; pos = sd.pos_x[i]; } else if( i==sd.n_entries ) { strain_hoop = sd.strains_hoop[i-1]; strain_radial = sd.strains_radial[i-1]; strain_axial = sd.strains_axial[i-1]; pos = sd.pos_x[i-1]; } else { /* get lattice strains from current neutron position */ /* use linear interpolation between two given positions */ strain_axial = (sd.strains_axial[i] - sd.strains_axial[i-1]) / (sd.pos_x[i] - sd.pos_x[i-1]) * (pos - sd.pos_x[i-1]) + sd.strains_axial[i-1]; strain_hoop = (sd.strains_hoop[i] - sd.strains_hoop[i-1]) / (sd.pos_x[i] - sd.pos_x[i-1]) * (pos - sd.pos_x[i-1]) + sd.strains_hoop[i-1]; strain_radial = (sd.strains_radial[i] - sd.strains_radial[i-1]) / (sd.pos_x[i] - sd.pos_x[i-1]) * (pos - sd.pos_x[i-1]) + sd.strains_radial[i-1]; } /* now take care of the neutron flight direction */ /* use sin2psi calculation to determine current dvalue */ double sin2psi; double dvalue; sin2psi = sin(acos( (x*vx + z*vz) / sqrt(x*x + z*z) / sqrt(vx*vx + vz*vz) )); sin2psi = sin2psi * sin2psi; double d_hoop = strain_hoop*sd.d0_hoop*1E-6+sd.d0_hoop; double d_radial = strain_radial*sd.d0_radial*1E-6+sd.d0_radial; dvalue = (d_hoop-d_radial) * sin2psi + d_radial; /* and now axial also... */ sin2psi = sin(acos( vy / sqrt(vx*vx + vy*vy + vz*vz) )); sin2psi = sin2psi * sin2psi; double d_axial = strain_axial*sd.d0_axial*1E-6+sd.d0_axial; dvalue = (dvalue-d_axial) * sin2psi + d_axial; /* re-init nxs calculation & adjust lattice spacings for all hkl...*/ for( i=0; idhkl = nxs_calcDhkl( hkl->h, hkl->k, hkl->l, &uc ); hkl->FSquare = nxs_calcFSquare( hkl, &uc ); } xsect_coherent = nxs_CoherentElastic(lambda, &uc ); xsect_incoherent = nxs_IncoherentElastic(lambda, &uc ) + nxs_IncoherentInelastic(lambda, &uc ) + nxs_CoherentInelastic(lambda, &uc ); xsect_absorption = nxs_Absorption(lambda, &uc ); xsect_total = xsect_coherent + xsect_incoherent + xsect_absorption; } /* path through the sample */ fullpath = velocity * (t2-t1); p_transmit = exp( -xsect_total * fullpath*1E2 / uc.volume ); /* check if neutron interacts with or transmits through the sample */ if( p_transmit < rand01() ) { double roulette_ball = rand01() * (xsect_total); double norm = lambda*lambda*1E-2 / 2.0 / uc.volume; /* ******************** */ /* SCATTER coherently */ /* ******************** */ if (roulette_ball <= xsect_coherent) { int j; int max_hkl = -1; double contrib = 0.0; while( max_hkl<(int)uc.nHKL-1 && 2.0*uc.hklList[max_hkl+1].dhkl-lambda > 1E-6 ) { max_hkl++; contrib += uc.hklList[max_hkl].FSquare * uc.hklList[max_hkl].multiplicity * uc.hklList[max_hkl].dhkl; } /* determine lattice plane (for scattering) */ roulette_ball = rand01() * contrib; contrib = 0.0; for( j=0; j 1) d_phi = 0; else d_phi = 2*asin(arg); } if (d_phi) { d_phi0 = 2*rand01()*fabs(d_phi); if (d_phi0 > d_phi) { d_phi0 = PI+(d_phi0-1.5*d_phi); } else { d_phi0=d_phi0-0.5*d_phi; } p *= d_phi/PI; } else d_phi0 = PI*randpm1(); vec_prod(tmp_vx,tmp_vy,tmp_vz, vx,vy,vz, 1,0,0); if (!tmp_vx && !tmp_vy && !tmp_vz) { tmp_vx=tmp_vz=0; tmp_vy=1; } /* v_out = rotate 'v' by 2*theta around tmp_v: Bragg angle */ rotate(vout_x,vout_y,vout_z, vx,vy,vz, 2.0*theta, tmp_vx,tmp_vy,tmp_vz); /* tmp_v = rotate v_out by d_phi around 'v' (Debye-Scherrer cone) */ rotate(tmp_vx,tmp_vy,tmp_vz, vout_x,vout_y,vout_z, d_phi0, vx, vy, vz); vx = tmp_vx; vy = tmp_vy; vz = tmp_vz; } /* ******************** */ /* SCATTER incoherently */ /* ******************** */ else if (roulette_ball <= xsect_coherent+xsect_incoherent) { /* check the incoherent switch */ if (IncohScat) { double solid_angle; randvec_target_rect_angular(&vx, &vy, &vz, &solid_angle, 0, 0, 1, 2.0*PI, d_phi*DEG2RAD, ROT_A_CURRENT_COMP); vx *= velocity; vy *= velocity; vz *= velocity; if (d_phi) p *= d_phi/PI; } /* end of if (bIncohScat) */ } else { /* neutron absorption -> remove neutron from trajectory */ ms_loop = 0; ABSORB; } /* end of if-else( roulette_ball <= xsect_coherent ) */ int err = 0; if( shape==0 && !cylinder_intersect(&t1, &t2, x, y, z, vx, vy, vz, radius, yheight) || t2<0 ) err=1; else if( shape==1 && !box_intersect(&t1, &t2, x, y, z, vx, vy, vz, xwidth, yheight, zthick) || t2<0 ) err=1; else if( shape==2 && !sphere_intersect(&t1, &t2, x, y, z, vx, vy, vz, radius) || t2<0 ) err=1; else if( shape==3 && !off_intersect(&t1, &t2, NULL, NULL, x, y, z, vx, vy, vz, offdata) || t2<0 ) err=1; if( err ) { /* Strange error */ fprintf(stderr, "sample_nxs: FATAL ERROR: Did not hit sample from inside.\n, t1=%f t2=%f\n", t1, t2); ABSORB; } t1 = 0.0; SCATTER; } /* end of if( p_transmit < rand01() ) */ else { /* else let the neutron simply transmit through the sample */ /* without any interaction or neutron weight change */ ms_loop = 0; } } /* end of while( ms_loop-- ) */ } /* end of if-else(bTransOnly) */ } /* end of if(box_intersect) */ } #line 11622 "tof_diffraction.c" } /* End of sample1=sample_nxs() SETTING parameter declarations. */ #undef V2L #undef sd #undef mu_factor #undef A #undef uc #undef t2 #undef t1 #undef fullpath #undef velocity #undef lambda #undef xsect_absorption #undef xsect_incoherent #undef xsect_coherent #undef xsect_total #undef p_transmit #undef nxs_init_success #undef intersect #undef isrect #undef MultiScat #undef IncohScat #undef TransOnly #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Label for restoring neutron */ mcabsorbCompsample1: if (RESTORE) /* restore if needed */ { RESTORE_NEUTRON(4, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); } #undef mcabsorbComp #undef p #undef sz #undef sy #undef sx #undef t #undef vz #undef vy #undef vx #undef z #undef y #undef x mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) /* TRACE Component sample [5] */ mccoordschange(mcposrsample, mcrotrsample, &mcnlx, &mcnly, &mcnlz, &mcnlvx, &mcnlvy, &mcnlvz, &mcnlsx, &mcnlsy, &mcnlsz); /* define label inside component sample (without coords transformations) */ mcJumpTrace_sample: SIG_MESSAGE("sample (Trace)"); mcDEBUG_COMP("sample") mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) #define x mcnlx #define y mcnly #define z mcnlz #define vx mcnlvx #define vy mcnlvy #define vz mcnlvz #define t mcnlt #define sx mcnlsx #define sy mcnlsy #define sz mcnlsz #define p mcnlp #define mcabsorbComp mcabsorbCompsample STORE_NEUTRON(5, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); mcScattered=0; mcRestore=0; mcNCounter[5]++; mcPCounter[5] += p; mcP2Counter[5] += p*p; #define mccompcurname sample #define mccompcurtype Arm #define mccompcurindex 5 #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Label for restoring neutron */ mcabsorbCompsample: if (RESTORE) /* restore if needed */ { RESTORE_NEUTRON(5, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); } #undef mcabsorbComp #undef p #undef sz #undef sy #undef sx #undef t #undef vz #undef vy #undef vx #undef z #undef y #undef x mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) /* TRACE Component beamstop [6] */ mccoordschange(mcposrbeamstop, mcrotrbeamstop, &mcnlx, &mcnly, &mcnlz, &mcnlvx, &mcnlvy, &mcnlvz, &mcnlsx, &mcnlsy, &mcnlsz); /* define label inside component beamstop (without coords transformations) */ mcJumpTrace_beamstop: SIG_MESSAGE("beamstop (Trace)"); mcDEBUG_COMP("beamstop") mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) #define x mcnlx #define y mcnly #define z mcnlz #define vx mcnlvx #define vy mcnlvy #define vz mcnlvz #define t mcnlt #define sx mcnlsx #define sy mcnlsy #define sz mcnlsz #define p mcnlp #define mcabsorbComp mcabsorbCompbeamstop STORE_NEUTRON(6, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); mcScattered=0; mcRestore=0; mcNCounter[6]++; mcPCounter[6] += p; mcP2Counter[6] += p*p; #define mccompcurname beamstop #define mccompcurtype Beamstop #define mccompcurindex 6 { /* Declarations of beamstop=Beamstop() SETTING parameters. */ MCNUM xmin = mccbeamstop_xmin; MCNUM xmax = mccbeamstop_xmax; MCNUM ymin = mccbeamstop_ymin; MCNUM ymax = mccbeamstop_ymax; MCNUM xwidth = mccbeamstop_xwidth; MCNUM yheight = mccbeamstop_yheight; MCNUM radius = mccbeamstop_radius; #line 59 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Beamstop.comp" { double Time = t; ALLOW_BACKPROP; PROP_Z0; Time = t - Time; if ((Time>=0) && ((radius!=0) && (x*x + y*y <= radius*radius)) || ((Time>=0) && (radius==0) && (x>xmin && xymin && yxmin && xymin && y= 0 && i < nt) { TOF_N[i]++; TOF_p[i] += p; TOF_p2[i] += p*p; SCATTER; } } if (restore_neutron) { RESTORE_NEUTRON(INDEX_CURRENT_COMP, x, y, z, vx, vy, vz, t, sx, sy, sz, p); } } #line 12014 "tof_diffraction.c" } /* End of tofmon=TOF_monitor() SETTING parameter declarations. */ #undef delta_t #undef t_max #undef t_min #undef TOF_p2 #undef TOF_p #undef TOF_N #undef nt #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Label for restoring neutron */ mcabsorbComptofmon: if (RESTORE) /* restore if needed */ { RESTORE_NEUTRON(7, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); } #undef mcabsorbComp #undef p #undef sz #undef sy #undef sx #undef t #undef vz #undef vy #undef vx #undef z #undef y #undef x mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) /* TRACE Component lmon [8] */ mccoordschange(mcposrlmon, mcrotrlmon, &mcnlx, &mcnly, &mcnlz, &mcnlvx, &mcnlvy, &mcnlvz, &mcnlsx, &mcnlsy, &mcnlsz); /* define label inside component lmon (without coords transformations) */ mcJumpTrace_lmon: SIG_MESSAGE("lmon (Trace)"); mcDEBUG_COMP("lmon") mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) #define x mcnlx #define y mcnly #define z mcnlz #define vx mcnlvx #define vy mcnlvy #define vz mcnlvz #define t mcnlt #define sx mcnlsx #define sy mcnlsy #define sz mcnlsz #define p mcnlp #define mcabsorbComp mcabsorbComplmon STORE_NEUTRON(8, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); mcScattered=0; mcRestore=0; mcNCounter[8]++; mcPCounter[8] += p; mcP2Counter[8] += p*p; #define mccompcurname lmon #define mccompcurtype L_monitor #define mccompcurindex 8 #define nL mcclmon_nL #define L_N mcclmon_L_N #define L_p mcclmon_L_p #define L_p2 mcclmon_L_p2 { /* Declarations of lmon=L_monitor() SETTING parameters. */ char* filename = mcclmon_filename; MCNUM xmin = mcclmon_xmin; MCNUM xmax = mcclmon_xmax; MCNUM ymin = mcclmon_ymin; MCNUM ymax = mcclmon_ymax; MCNUM xwidth = mcclmon_xwidth; MCNUM yheight = mcclmon_yheight; MCNUM Lmin = mcclmon_Lmin; MCNUM Lmax = mcclmon_Lmax; MCNUM restore_neutron = mcclmon_restore_neutron; #line 83 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/L_monitor.comp" { int i; double L; PROP_Z0; if (x>xmin && xymin && y= 0 && i < nL) { L_N[i]++; L_p[i] += p; L_p2[i] += p*p; SCATTER; } } if (restore_neutron) { RESTORE_NEUTRON(INDEX_CURRENT_COMP, x, y, z, vx, vy, vz, t, sx, sy, sz, p); } } #line 12163 "tof_diffraction.c" } /* End of lmon=L_monitor() SETTING parameter declarations. */ #undef L_p2 #undef L_p #undef L_N #undef nL #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Label for restoring neutron */ mcabsorbComplmon: if (RESTORE) /* restore if needed */ { RESTORE_NEUTRON(8, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); } #undef mcabsorbComp #undef p #undef sz #undef sy #undef sx #undef t #undef vz #undef vy #undef vx #undef z #undef y #undef x mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) /* TRACE Component rot90 [9] */ mccoordschange(mcposrrot90, mcrotrrot90, &mcnlx, &mcnly, &mcnlz, &mcnlvx, &mcnlvy, &mcnlvz, &mcnlsx, &mcnlsy, &mcnlsz); /* define label inside component rot90 (without coords transformations) */ mcJumpTrace_rot90: SIG_MESSAGE("rot90 (Trace)"); mcDEBUG_COMP("rot90") mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) #define x mcnlx #define y mcnly #define z mcnlz #define vx mcnlvx #define vy mcnlvy #define vz mcnlvz #define t mcnlt #define sx mcnlsx #define sy mcnlsy #define sz mcnlsz #define p mcnlp #define mcabsorbComp mcabsorbComprot90 STORE_NEUTRON(9, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); mcScattered=0; mcRestore=0; mcNCounter[9]++; mcPCounter[9] += p; mcP2Counter[9] += p*p; #define mccompcurname rot90 #define mccompcurtype Arm #define mccompcurindex 9 #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Label for restoring neutron */ mcabsorbComprot90: if (RESTORE) /* restore if needed */ { RESTORE_NEUTRON(9, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); } #undef mcabsorbComp #undef p #undef sz #undef sy #undef sx #undef t #undef vz #undef vy #undef vx #undef z #undef y #undef x mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) /* TRACE Component blende [10] */ mccoordschange(mcposrblende, mcrotrblende, &mcnlx, &mcnly, &mcnlz, &mcnlvx, &mcnlvy, &mcnlvz, &mcnlsx, &mcnlsy, &mcnlsz); /* define label inside component blende (without coords transformations) */ mcJumpTrace_blende: SIG_MESSAGE("blende (Trace)"); mcDEBUG_COMP("blende") mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) #define x mcnlx #define y mcnly #define z mcnlz #define vx mcnlvx #define vy mcnlvy #define vz mcnlvz #define t mcnlt #define sx mcnlsx #define sy mcnlsy #define sz mcnlsz #define p mcnlp #define mcabsorbComp mcabsorbCompblende STORE_NEUTRON(10, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); mcScattered=0; mcRestore=0; mcNCounter[10]++; mcPCounter[10] += p; mcP2Counter[10] += p*p; #define mccompcurname blende #define mccompcurtype Slit #define mccompcurindex 10 { /* Declarations of blende=Slit() SETTING parameters. */ MCNUM xmin = mccblende_xmin; MCNUM xmax = mccblende_xmax; MCNUM ymin = mccblende_ymin; MCNUM ymax = mccblende_ymax; MCNUM radius = mccblende_radius; MCNUM xwidth = mccblende_xwidth; MCNUM yheight = mccblende_yheight; #line 56 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Slit.comp" { PROP_Z0; if (((radius == 0) && (xxmax || yymax)) || ((radius != 0) && (x*x + y*y > radius*radius))) ABSORB; else SCATTER; } #line 12392 "tof_diffraction.c" } /* End of blende=Slit() SETTING parameter declarations. */ #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* Label for restoring neutron */ mcabsorbCompblende: if (RESTORE) /* restore if needed */ { RESTORE_NEUTRON(10, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); } #undef mcabsorbComp #undef p #undef sz #undef sy #undef sx #undef t #undef vz #undef vy #undef vx #undef z #undef y #undef x mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) /* TRACE Component detector [11] */ mccoordschange(mcposrdetector, mcrotrdetector, &mcnlx, &mcnly, &mcnlz, &mcnlvx, &mcnlvy, &mcnlvz, &mcnlsx, &mcnlsy, &mcnlsz); /* define label inside component detector (without coords transformations) */ mcJumpTrace_detector: SIG_MESSAGE("detector (Trace)"); mcDEBUG_COMP("detector") mcDEBUG_STATE( mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp) #define x mcnlx #define y mcnly #define z mcnlz #define vx mcnlvx #define vy mcnlvy #define vz mcnlvz #define t mcnlt #define sx mcnlsx #define sy mcnlsy #define sz mcnlsz #define p mcnlp #define mcabsorbComp mcabsorbCompdetector STORE_NEUTRON(11, mcnlx, mcnly, mcnlz, mcnlvx, mcnlvy, mcnlvz, mcnlt, mcnlsx, mcnlsy, mcnlsz, mcnlp); mcScattered=0; mcRestore=0; mcNCounter[11]++; mcPCounter[11] += p; mcP2Counter[11] += p*p; #define mccompcurname detector #define mccompcurtype PSD_monitor #define mccompcurindex 11 #define nx mccdetector_nx #define ny mccdetector_ny #define PSD_N mccdetector_PSD_N #define PSD_p mccdetector_PSD_p #define PSD_p2 mccdetector_PSD_p2 { /* Declarations of detector=PSD_monitor() SETTING parameters. */ char* filename = mccdetector_filename; MCNUM xmin = mccdetector_xmin; MCNUM xmax = mccdetector_xmax; MCNUM ymin = mccdetector_ymin; MCNUM ymax = mccdetector_ymax; MCNUM xwidth = mccdetector_xwidth; MCNUM yheight = mccdetector_yheight; MCNUM restore_neutron = mccdetector_restore_neutron; #line 82 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/PSD_monitor.comp" { int i,j; PROP_Z0; if (x>xmin && xymin && y 0 && yheight ) { /* cylinder */ circle("xz", 0, yheight/2.0, 0, radius); circle("xz", 0, -yheight/2.0, 0, radius); line(-radius, -yheight/2.0, 0, -radius, +yheight/2.0, 0); line(+radius, -yheight/2.0, 0, +radius, +yheight/2.0, 0); line(0, -yheight/2.0, -radius, 0, +yheight/2.0, -radius); line(0, -yheight/2.0, +radius, 0, +yheight/2.0, +radius); if( thickness ) { double radius_i=radius-thickness; circle("xz", 0, yheight/2.0, 0, radius_i); circle("xz", 0, -yheight/2.0, 0, radius_i); line(-radius_i, -yheight/2.0, 0, -radius_i, +yheight/2.0, 0); line(+radius_i, -yheight/2.0, 0, +radius_i, +yheight/2.0, 0); line(0, -yheight/2.0, -radius_i, 0, +yheight/2.0, -radius_i); line(0, -yheight/2.0, +radius_i, 0, +yheight/2.0, +radius_i); } } else if( xwidth && yheight ) { /* box/rectangle XY */ double xmin = -0.5*xwidth; double xmax = 0.5*xwidth; double ymin = -0.5*yheight; double ymax = 0.5*yheight; double zmin = -0.5*zthick; double zmax = 0.5*zthick; multiline(5, xmin, ymin, zmin, xmax, ymin, zmin, xmax, ymax, zmin, xmin, ymax, zmin, xmin, ymin, zmin); multiline(5, xmin, ymin, zmax, xmax, ymin, zmax, xmax, ymax, zmax, xmin, ymax, zmax, xmin, ymin, zmax); line(xmin, ymin, zmin, xmin, ymin, zmax); line(xmax, ymin, zmin, xmax, ymin, zmax); line(xmin, ymax, zmin, xmin, ymax, zmax); line(xmax, ymax, zmin, xmax, ymax, zmax); } else if ( radius > 0 && !yheight ) { /* sphere */ circle("xy", 0, 0.0, 0, radius); circle("xz", 0, 0.0, 0, radius); circle("yz", 0, 0.0, 0, radius); } } #line 13022 "tof_diffraction.c" } /* End of sample1=sample_nxs() SETTING parameter declarations. */ #undef V2L #undef sd #undef mu_factor #undef A #undef uc #undef t2 #undef t1 #undef fullpath #undef velocity #undef lambda #undef xsect_absorption #undef xsect_incoherent #undef xsect_coherent #undef xsect_total #undef p_transmit #undef nxs_init_success #undef intersect #undef isrect #undef MultiScat #undef IncohScat #undef TransOnly #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* MCDISPLAY code for component 'sample'. */ SIG_MESSAGE("sample (McDisplay)"); printf("MCDISPLAY: component %s\n", "sample"); #define mccompcurname sample #define mccompcurtype Arm #define mccompcurindex 5 #line 40 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Arm.comp" { /* A bit ugly; hard-coded dimensions. */ magnify(""); line(0,0,0,0.2,0,0); line(0,0,0,0,0.2,0); line(0,0,0,0,0,0.2); } #line 13063 "tof_diffraction.c" #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* MCDISPLAY code for component 'beamstop'. */ SIG_MESSAGE("beamstop (McDisplay)"); printf("MCDISPLAY: component %s\n", "beamstop"); #define mccompcurname beamstop #define mccompcurtype Beamstop #define mccompcurindex 6 { /* Declarations of beamstop=Beamstop() SETTING parameters. */ MCNUM xmin = mccbeamstop_xmin; MCNUM xmax = mccbeamstop_xmax; MCNUM ymin = mccbeamstop_ymin; MCNUM ymax = mccbeamstop_ymax; MCNUM xwidth = mccbeamstop_xwidth; MCNUM yheight = mccbeamstop_yheight; MCNUM radius = mccbeamstop_radius; #line 72 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Beamstop.comp" { magnify("xy"); if (radius != 0) circle("xy", 0, 0, 0, radius); else multiline(5, (double)xmin, (double)ymin, 0.0, (double)xmax, (double)ymin, 0.0, (double)xmax, (double)ymax, 0.0, (double)xmin, (double)ymax, 0.0, (double)xmin, (double)ymin, 0.0); } #line 13094 "tof_diffraction.c" } /* End of beamstop=Beamstop() SETTING parameter declarations. */ #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* MCDISPLAY code for component 'tofmon'. */ SIG_MESSAGE("tofmon (McDisplay)"); printf("MCDISPLAY: component %s\n", "tofmon"); #define mccompcurname tofmon #define mccompcurtype TOF_monitor #define mccompcurindex 7 #define nt mcctofmon_nt #define TOF_N mcctofmon_TOF_N #define TOF_p mcctofmon_TOF_p #define TOF_p2 mcctofmon_TOF_p2 #define t_min mcctofmon_t_min #define t_max mcctofmon_t_max #define delta_t mcctofmon_delta_t { /* Declarations of tofmon=TOF_monitor() SETTING parameters. */ char* filename = mcctofmon_filename; MCNUM xmin = mcctofmon_xmin; MCNUM xmax = mcctofmon_xmax; MCNUM ymin = mcctofmon_ymin; MCNUM ymax = mcctofmon_ymax; MCNUM xwidth = mcctofmon_xwidth; MCNUM yheight = mcctofmon_yheight; MCNUM tmin = mcctofmon_tmin; MCNUM tmax = mcctofmon_tmax; MCNUM dt = mcctofmon_dt; MCNUM restore_neutron = mcctofmon_restore_neutron; #line 125 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/TOF_monitor.comp" { magnify("xy"); multiline(5, (double)xmin, (double)ymin, 0.0, (double)xmax, (double)ymin, 0.0, (double)xmax, (double)ymax, 0.0, (double)xmin, (double)ymax, 0.0, (double)xmin, (double)ymin, 0.0); } #line 13134 "tof_diffraction.c" } /* End of tofmon=TOF_monitor() SETTING parameter declarations. */ #undef delta_t #undef t_max #undef t_min #undef TOF_p2 #undef TOF_p #undef TOF_N #undef nt #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* MCDISPLAY code for component 'lmon'. */ SIG_MESSAGE("lmon (McDisplay)"); printf("MCDISPLAY: component %s\n", "lmon"); #define mccompcurname lmon #define mccompcurtype L_monitor #define mccompcurindex 8 #define nL mcclmon_nL #define L_N mcclmon_L_N #define L_p mcclmon_L_p #define L_p2 mcclmon_L_p2 { /* Declarations of lmon=L_monitor() SETTING parameters. */ char* filename = mcclmon_filename; MCNUM xmin = mcclmon_xmin; MCNUM xmax = mcclmon_xmax; MCNUM ymin = mcclmon_ymin; MCNUM ymax = mcclmon_ymax; MCNUM xwidth = mcclmon_xwidth; MCNUM yheight = mcclmon_yheight; MCNUM Lmin = mcclmon_Lmin; MCNUM Lmax = mcclmon_Lmax; MCNUM restore_neutron = mcclmon_restore_neutron; #line 117 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/L_monitor.comp" { magnify("xy"); multiline(5, (double)xmin, (double)ymin, 0.0, (double)xmax, (double)ymin, 0.0, (double)xmax, (double)ymax, 0.0, (double)xmin, (double)ymax, 0.0, (double)xmin, (double)ymin, 0.0); } #line 13177 "tof_diffraction.c" } /* End of lmon=L_monitor() SETTING parameter declarations. */ #undef L_p2 #undef L_p #undef L_N #undef nL #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* MCDISPLAY code for component 'rot90'. */ SIG_MESSAGE("rot90 (McDisplay)"); printf("MCDISPLAY: component %s\n", "rot90"); #define mccompcurname rot90 #define mccompcurtype Arm #define mccompcurindex 9 #line 40 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Arm.comp" { /* A bit ugly; hard-coded dimensions. */ magnify(""); line(0,0,0,0.2,0,0); line(0,0,0,0,0.2,0); line(0,0,0,0,0,0.2); } #line 13201 "tof_diffraction.c" #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* MCDISPLAY code for component 'blende'. */ SIG_MESSAGE("blende (McDisplay)"); printf("MCDISPLAY: component %s\n", "blende"); #define mccompcurname blende #define mccompcurtype Slit #define mccompcurindex 10 { /* Declarations of blende=Slit() SETTING parameters. */ MCNUM xmin = mccblende_xmin; MCNUM xmax = mccblende_xmax; MCNUM ymin = mccblende_ymin; MCNUM ymax = mccblende_ymax; MCNUM radius = mccblende_radius; MCNUM xwidth = mccblende_xwidth; MCNUM yheight = mccblende_yheight; #line 66 "/mnt/lustre/apps/centos73/mcstas/2.4.1/optics/Slit.comp" { magnify("xy"); if (radius == 0) { double xw, yh; xw = (xmax - xmin)/2.0; yh = (ymax - ymin)/2.0; multiline(3, xmin-xw, (double)ymax, 0.0, (double)xmin, (double)ymax, 0.0, (double)xmin, ymax+yh, 0.0); multiline(3, xmax+xw, (double)ymax, 0.0, (double)xmax, (double)ymax, 0.0, (double)xmax, ymax+yh, 0.0); multiline(3, xmin-xw, (double)ymin, 0.0, (double)xmin, (double)ymin, 0.0, (double)xmin, ymin-yh, 0.0); multiline(3, xmax+xw, (double)ymin, 0.0, (double)xmax, (double)ymin, 0.0, (double)xmax, ymin-yh, 0.0); } else { circle("xy",0,0,0,radius); } } #line 13243 "tof_diffraction.c" } /* End of blende=Slit() SETTING parameter declarations. */ #undef mccompcurname #undef mccompcurtype #undef mccompcurindex /* MCDISPLAY code for component 'detector'. */ SIG_MESSAGE("detector (McDisplay)"); printf("MCDISPLAY: component %s\n", "detector"); #define mccompcurname detector #define mccompcurtype PSD_monitor #define mccompcurindex 11 #define nx mccdetector_nx #define ny mccdetector_ny #define PSD_N mccdetector_PSD_N #define PSD_p mccdetector_PSD_p #define PSD_p2 mccdetector_PSD_p2 { /* Declarations of detector=PSD_monitor() SETTING parameters. */ char* filename = mccdetector_filename; MCNUM xmin = mccdetector_xmin; MCNUM xmax = mccdetector_xmax; MCNUM ymin = mccdetector_ymin; MCNUM ymax = mccdetector_ymax; MCNUM xwidth = mccdetector_xwidth; MCNUM yheight = mccdetector_yheight; MCNUM restore_neutron = mccdetector_restore_neutron; #line 112 "/mnt/lustre/apps/centos73/mcstas/2.4.1/monitors/PSD_monitor.comp" { magnify("xy"); multiline(5, (double)xmin, (double)ymin, 0.0, (double)xmax, (double)ymin, 0.0, (double)xmax, (double)ymax, 0.0, (double)xmin, (double)ymax, 0.0, (double)xmin, (double)ymin, 0.0); } #line 13278 "tof_diffraction.c" } /* End of detector=PSD_monitor() SETTING parameter declarations. */ #undef PSD_p2 #undef PSD_p #undef PSD_N #undef ny #undef nx #undef mccompcurname #undef mccompcurtype #undef mccompcurindex printf("MCDISPLAY: end\n"); } /* end display */ #undef magnify #undef line #undef dashed_line #undef multiline #undef rectangle #undef box #undef circle /* end of generated C code tof_diffraction.c */