diff --git a/ChangeLog b/ChangeLog index c35706326..bdf7886fd 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,34 +1,43 @@ -2018-03-09 Steve Morley - * Release: v1.5.16 +2019-11-05 Mark Galassi - * tests: revised and expanded test suite, github repo set to use Travis - CI + * libLanlGeoMag/Makefile.am: took out again the Images/ directory + because it makes tarballs and RPMs too big (on the order of 300meg + instead of 50meg). - * Lgm_QinDenton: updated defaults, changed handling of missing data - files + * Makefile.am (EXTRA_DIST): re-added the Images directory that was + commented out. This is necessary for a "make install" from the + tarball to work. - * Lgm_Ellipsoid: added shapes, intersections, etc. + * lanlgeomag.spec.in: added some Requires and BuildRequires, and + took out the requirement for Perl since we configure with + --disable-perl. Also started using appropriate RPM macros. - * Tools: Command line utils for Magnetic Ephemeris files and Last - Closed Drift Shell calculation + * configure.ac: updated THE_PKG_RELEASE to 7; this affects the RPM + package release number. - * ViewDriftShell: Updates to improve portability and UI + * Doxyfile: added USE_MATHJAX, the compact latex option, and the + amsmath package, which is needed for the \text{'} that comes up + occasionally in the doxygen docs. - * ComputeLstar: Behavior in Shabansky orbits now set by flag in - LstarInfo struct + * Doc/LanlGeoMag.tag.in, configure.ac: the LanlGeoMag.tag file was + required for "make dist" but did not exist. I have added it, + built from a .in file so it can have a version number in it. + Modified configure.ac to generate Doc/LanlGeoMag.tag from + Doc/LanlGeoMag.tag.in - * Lgm_CTrans: Added JPL DE421 to obtain Sun vector (now have DE, high - accuracy and low accuracy) +2017-11-16 Mark Galassi - * TS07: TS07 magnetic field model fully enabled. Requires coefficient - files in same location/format as IRBEMlib. + * configure.ac: releasing version 1.5.16. - * Other: More changes since this file was last updated than can be - encapsulated here. OSS release and GitHub hosting means that commit - history is now publicly available. + * lanlgeomag.spec.in: added --disable-perl for building RPMs. + + * libLanlGeoMag/Makefile.am (EXTRA_DIST): took the Images + directory out of this list because it makes the tarball + distribution too big. 2011-07-08 Mike Henderson - * configure.ac: added LGM_INDEX_DATA_DIR to locate where to find index data (e.g. Kp, Dst, AE). + * configure.ac: added LGM_INDEX_DATA_DIR to locate where to find + index data (e.g. Kp, Dst, AE). 2011-04-25 Mark Galassi * configure.ac, lanlgeomag.spec.in: started maintaining a .spec.in diff --git a/Doc/LanlGeoMag.tag.in b/Doc/LanlGeoMag.tag.in new file mode 100644 index 000000000..d78bda934 --- /dev/null +++ b/Doc/LanlGeoMag.tag.in @@ -0,0 +1 @@ +@VERSION@ diff --git a/Doxyfile b/Doxyfile index a67c4b3d0..a8c6c4dc1 100644 --- a/Doxyfile +++ b/Doxyfile @@ -1230,7 +1230,7 @@ FORMULA_TRANSPARENT = YES # output. When enabled you may also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. -USE_MATHJAX = NO +USE_MATHJAX = YES # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination @@ -1290,7 +1290,7 @@ LATEX_OUTPUT = latex # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. -LATEX_CMD_NAME = latex +LATEX_CMD_NAME = pdflatex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the @@ -1302,7 +1302,7 @@ MAKEINDEX_CMD_NAME = makeindex # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. -COMPACT_LATEX = NO +COMPACT_LATEX = YES # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and @@ -1313,7 +1313,7 @@ PAPER_TYPE = $(PAPER_SIZE) # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. -EXTRA_PACKAGES = +EXTRA_PACKAGES = amsmath # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until diff --git a/Examples/CoordQuickStart/Makefile b/Examples/CoordQuickStart/Makefile index a4a6c2e58..7225fc01d 100644 --- a/Examples/CoordQuickStart/Makefile +++ b/Examples/CoordQuickStart/Makefile @@ -2,7 +2,7 @@ HDF5FLAGS = `pkg-config hdf5 --cflags --libs 2>/dev/null` LGMFLAGS = `pkg-config lgm --cflags --libs` -all : CoordQuickStart CoordTransTest compareGSE +all : CoordQuickStart CoordTransTest CoordQuickStart: CoordQuickStart.c gcc CoordQuickStart.c -Wall $(LGMFLAGS) $(HDF5FLAGS) -o CoordQuickStart @@ -10,8 +10,5 @@ CoordQuickStart: CoordQuickStart.c CoordTransTest: CoordTransTest.c gcc CoordTransTest.c -Wall $(LGMFLAGS) $(HDF5FLAGS) -o CoordTransTest -compareGSE: compareGSE.c - gcc compareGSE.c -Wall $(LGMFLAGS) $(HDF5FLAGS) -o compareGSE - clean: - rm CoordQuickStart CoordTransTest compareGSE + rm CoordQuickStart CoordTransTest diff --git a/Examples/FluxToPSD/FluxToPSD.c b/Examples/FluxToPSD/FluxToPSD.c index b4f80aa58..6f9717883 100755 --- a/Examples/FluxToPSD/FluxToPSD.c +++ b/Examples/FluxToPSD/FluxToPSD.c @@ -1,9 +1,8 @@ /* CHECK ME FOR MEMORY LEAKS..... -THIS ALSO eeds some argument changes... +THIS ALSO needs some argument changes... e.g. The Mu's K's instead of pitch angles... */ -#include "CDFUtils.h" #include #include #include @@ -14,24 +13,21 @@ e.g. The Mu's K's instead of pitch angles... #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #define KP_DEFAULT 0 void InterpVec( double *JD, Lgm_Vector *Ugsm, int n1, double cJD, Lgm_Vector *v ); void InterpArr( double *JD, double *y, int n, double cJD, double *r ) ; -void WriteHDF5PSDHeader(hid_t file, int nMu, int nK, double *Mu, double *K); -void WriteHDF5PSDData(hid_t file, int i, int nMu, int nK, char **IsoTimes, - double *PsdLstar, double *AlphaOfK, double **PSD); const char *argp_program_version = "FluxToPSD 1.0"; const char *argp_program_bug_address = ""; @@ -39,7 +35,7 @@ static char doc[] = "Converts Flux to PSD. Blah Blah"; // Mandatory arguments #define nArgs 2 -static char ArgsDoc[] = "MergedFluxFile StdPsdFile"; +static char ArgsDoc[] = "StdFluxFile StdPsdFile"; /* @@ -56,21 +52,18 @@ static char ArgsDoc[] = "MergedFluxFile StdPsdFile"; static struct argp_option Options[] = { {"IntModel", 'i', "internal_model", 0, "Internal Magnetic Field Model to use. Default is IGRF." }, {"ExtModel", 'e', "external_model", 0, "External Magnetic Field Model to use. Default is T89." }, - {"ModelTime", 'T', "ISO8601_time_string", 0, "Force the model to use parameters for the given date/time. This can be used to force the model to be static instead of dynamic." }, - {"Mus", 'M', "\"start_Mu, end_Mu, nMu\"", 0, "Mu values to compute. Default is \"5, 5000.0, 18\"." }, + {"Mus", 'M', "\"start_Mu, end_Mu, nMu\"", 0, "Mu values to compute. Default is \"1, 2000.0, 18\"." }, {"Ks", 'K', "\"start_K, end_K, nK\"", 0, "K values to compute. Default is \"0.01, 10.0, 18\"." }, {"FootPointHeight", 'f', "height", 0, "Footpoint height in km. Default is 100km." }, {"Quality", 'q', "quality", 0, "Quality to use for L* calculations. Default is 3." }, - {"FitType", 't', "fit_type", 0, "Fit type for PSD energy spectrum: default (0) is 2 rel. Maxwellians, set to 1 for spline fit."}, {"StartDate", 'S', "yyyymmdd", 0, "StartDate " }, {"EndDate", 'E', "yyyymmdd", 0, "EndDate " }, {"Append", 'a', 0, 0, "Append to OutFile instead of creating a new one" }, -// {"UseEop", 'e', 0, 0, "Use Earth Orientation Parameters whn comoputing ephemerii" }, + {"UseEop", 'e', 0, 0, "Use Earth Orientation Parameters whn comoputing ephemerii" }, {"Colorize", 'c', 0, 0, "Colorize output" }, {"Force", 'F', 0, 0, "Overwrite output file even if it already exists" }, - {"verbose", 'v', "verbosity", 0, "Produce verbose output" }, + {"verbose", 'v', 0, OPTION_ARG_OPTIONAL, "Produce verbose output" }, {"silent", 's', 0, OPTION_ARG_OPTIONAL | OPTION_ALIAS }, - {"nchannels", 'n', "num_channels", 0, "Use first n energy channels" }, { 0 } }; @@ -78,7 +71,6 @@ struct Arguments { char *args[ nArgs ]; int silent; int verbose; - int nchannels; double StartMu; double EndMu; @@ -98,14 +90,9 @@ struct Arguments { int Append; int UseEop; - int FitType; - long int StartDate; long int EndDate; - - int FixModelDateTime; - char ModelDateTime[80]; }; @@ -116,9 +103,6 @@ static error_t parse_opt (int key, char *arg, struct argp_state *state) { know is a pointer to our arguments structure. */ struct Arguments *arguments = state->input; switch( key ) { - case 'a': // Append - arguments->Append = 1; - break; case 'S': // start date sscanf( arg, "%ld", &arguments->StartDate ); break; @@ -131,10 +115,6 @@ static error_t parse_opt (int key, char *arg, struct argp_state *state) { case 'i': // inbternal model strcpy( arguments->IntModel, arg ); break; - case 'T': // Date/time to use for forcing model parameters to be static. - strcpy( arguments->ModelDateTime, arg ); - arguments->FixModelDateTime = 1; - break; case 'K': sscanf( arg, "%lf, %lf, %d", &arguments->StartK, &arguments->EndK, &arguments->nK ); break; @@ -157,13 +137,7 @@ static error_t parse_opt (int key, char *arg, struct argp_state *state) { arguments->silent = 1; break; case 'v': - arguments->verbose = atoi( arg ); - break; - case 'n': - arguments->nchannels = atoi( arg ); - break; - case 't': - arguments->FitType = atoi( arg ); + arguments->verbose = 1; break; case ARGP_KEY_ARG: if (state->arg_num >= nArgs) { @@ -188,28 +162,31 @@ static struct argp argp = { Options, parse_opt, ArgsDoc, doc }; + /* - * + * Compute magnetic ephemerii of S/C from input file that contains S/C position in GEO LAt/Lon/Rad */ int main( int argc, char *argv[] ){ struct Arguments arguments; Lgm_CTrans *c = Lgm_init_ctrans( 0 ); - Lgm_DateTime ModelDateTime; + Lgm_Vector U; + Lgm_DateTime UTC; Lgm_Eop *e = Lgm_init_eop( 0 ); Lgm_EopOne eop; - int FixModelDateTime; - int i, iii, jjj, kk; + int i, iii, jjj; char InputFilename[1024]; char OutputFilename[1024]; char IntModel[20], ExtModel[20]; - int AppendMode, UseEop, Colorize, Force, nv, Quality; - double FootpointHeight; - long int StartDate, EndDate, Date __attribute__((unused)); + int AppendMode, UseEop, Colorize, Force, nv; + double Inc, Alpha[1000], FootpointHeight; + int nAlpha, Quality; + long int StartDate, EndDate, Date; int sYear, sMonth, sDay, sDoy, eYear, eMonth, eDay, eDoy, Year, Month, Day; int cYear, cMonth, cDay, cDoy; double sJD, eJD, JD, Time, cJD; + Lgm_QinDentonOne p; hsize_t dims[3]; double *Flux_Energy; double *Flux_Alpha; @@ -219,85 +196,74 @@ int main( int argc, char *argv[] ){ double **MagEphem_Lstar; double *MagEphem_Alpha; double ***J; - int fromHDF, retval __attribute__((unused)); + /* - * App-specific declarations + * App-specific declartations */ // Lgm_CTrans *c = Lgm_init_ctrans( 0 ); Lgm_DateTime d; - Lgm_Vector u, v, v_geo, Ugsm[300]; + Lgm_Vector u, v, Ugsm[300]; Lgm_FluxToPsd *f2p; + Lgm_PsdToFlux *p2f; Lgm_DateTime UTC_DateTime; - Lgm_MagModelInfo *mInfo; + Lgm_MagModelInfo *mInfo, *mInfo2; Lgm_QinDentonOne QinDen; double *E, *A, **J_DIFF; - int nE, nA, j, n, k, nTimes, MagEphem_nAlpha; + int nE, nA, j, n, k, n1, nTimes, MagEphem_nAlpha; double *Mu, *K, *LstarOfK, *AlphaOfK, *PsdLstar; int nMu, nK; - int OverRideKp; - double T89Q_Kp; - char Line[5000], **IsoTimes, buf[512], FillStr[20], fitDesc[25]; + double f, p2c2, df, sa; + double S[100], a, b, r; + char Line[5000], **IsoTimes; + double MagEphem_JD1[300]; + long int pos; + FILE *fp; hid_t file; - hid_t atype; hid_t space; - herr_t status __attribute__((unused)); - - hsize_t Dims[4], DataSet, MemSpace, SlabSize[4]; - CDFid id; - CDFstatus cdf_status; - int Ni, Nj, Nk, numMaxw, fitMaxw; - long numDims, dimSizes[CDF_MAX_DIMS], numRecs; - char varName[CDF_VAR_NAME_LEN256+1]; - long dataType, numElems, recVary, dimVarys[CDF_MAX_DIMS]; - double **Position, ***FEDU; - double *Epoch = NULL; - double *Flux_Energy_Tmp; - double *Flux_Alpha_Tmp; - double **FEDU_Lstar_Tmp; - char **ProcessedTime = NULL; - Lgm_DateTime CurrentUTC; - int nProcTimes; - int H5_nT; - int iTime; - int AppendFlag; + hid_t TimeDataSet, TimeMemSpace; + hsize_t TimeOffset[1] = { 0 }; + hsize_t TimeDims[1] = { 1 }; + hsize_t TimeSlabSize[1] = { 1 }; + + hid_t LstarDataSet, LstarMemSpace; + hsize_t LstarOffset[2] = { 0, 0, }; + hsize_t LstarDims[2] = { 1, 18, }; + hsize_t LstarSlabSize[2] = { 1, 18, }; + + hid_t PsdDataSet, PsdMemSpace; + hsize_t PsdOffset[3] = { 0, 0, 0 }; + hsize_t PsdDims[3] = { 1, 18, 18 }; + hsize_t PsdSlabSize[3] = { 1, 18, 18}; + + herr_t status; + /* * Default option values. */ - arguments.StartMu = 5.0; // start Mu [MeV/G] - arguments.EndMu = 5000.0; // stop Mu [MeV/G] - arguments.nMu = 18; // 18 Mus - arguments.StartK = 0.01; // start K [Re G^.5] - arguments.EndK = 10.0; // stop K [Re G^.5] - arguments.nK = 18; // 18 K - arguments.silent = 0; - arguments.verbose = 0; - arguments.nchannels = 0; - arguments.Quality = 3; - arguments.Colorize = 0; - arguments.Force = 0; - arguments.Append = 0; - arguments.UseEop = 0; - arguments.FixModelDateTime = 0; - arguments.StartDate = -1; - arguments.EndDate = -1; - arguments.FootPointHeight = 100.0; // km - numMaxw = 2; - arguments.FitType = 0; //0 for 2 Maxwellians, 1 for spline - strcpy( arguments.IntModel, "IGRF" ); - strcpy( arguments.ExtModel, "T89" ); - strcpy( arguments.ModelDateTime, "" ); - fitMaxw = arguments.FitType; - if ( fitMaxw==0 ) { - strcpy( fitDesc, "Double Maxwell-Juttner" ); - } else { - strcpy( fitDesc, "B-spline" ); - } + arguments.StartMu = 1.0; // start Mu [MeV/G] + arguments.EndMu = 2000.0; // stop Mu [MeV/G] + arguments.nMu = 18; // 18 Mus + arguments.StartK = 0.01; // start K [Re G^.5] + arguments.EndK = 10.0; // stop K [Re G^.5] + arguments.nK = 18; // 18 K + arguments.silent = 0; + arguments.verbose = 0; + arguments.Quality = 3; + arguments.Colorize = 0; + arguments.Force = 0; + arguments.Append = 0; + arguments.UseEop = 0; + arguments.StartDate = -1; + arguments.EndDate = -1; + arguments.FootPointHeight = 100.0; // km + strcpy( arguments.IntModel, "IGRF" ); + strcpy( arguments.ExtModel, "T89" ); /* @@ -315,21 +281,17 @@ int main( int argc, char *argv[] ){ /* * Set other options */ - FootpointHeight = arguments.FootPointHeight; - Quality = arguments.Quality; - Colorize = arguments.Colorize; - Force = arguments.Force; - AppendMode = arguments.Append; - UseEop = arguments.UseEop; - StartDate = arguments.StartDate; - EndDate = arguments.EndDate; - FixModelDateTime = arguments.FixModelDateTime; + FootpointHeight = arguments.FootPointHeight; + Quality = arguments.Quality; + Colorize = arguments.Colorize; + Force = arguments.Force; + AppendMode = arguments.Append; + UseEop = arguments.UseEop; + StartDate = arguments.StartDate; + EndDate = arguments.EndDate; strcpy( IntModel, arguments.IntModel ); strcpy( ExtModel, arguments.ExtModel ); - if ( FixModelDateTime ) IsoTimeStringToDateTime( arguments.ModelDateTime, &ModelDateTime, c ); - - @@ -379,17 +341,13 @@ int main( int argc, char *argv[] ){ } printf( "\t Internal Model: %s\n", IntModel ); printf( "\t External Model: %s\n", ExtModel ); - printf( "\t Spectral Fit: %s\n", fitDesc ); - if ( FixModelDateTime ) { - printf( "\t Model Params Fixed to: %s\n", arguments.ModelDateTime ); - } printf( "\t FootpointHeight [km]: %g\n", FootpointHeight ); printf( "\t L* Quality: %d\n", Quality ); printf( "\t Force output: %s\n", Force ? "yes" : "no" ); - printf( "\t Append to OutputFile: %s\n", AppendMode ? "yes" : "no" ); + //printf( "\t Append to OutputFile: %s\n", AppendMode ? "yes" : "no" ); printf( "\t Use Eop: %s\n", UseEop ? "yes" : "no" ); printf( "\t Colorize Thread Output: %d\n", Colorize ); - printf( "\t Verbose: %d\n", arguments.verbose); + printf( "\t Verbose: %s\n", arguments.verbose ? "yes" : "no" ); printf( "\t Silent: %s\n", arguments.silent ? "yes" : "no" ); if ( (StartDate > 0)&&(EndDate > 0) ){ printf( "\t StartDate: %ld\n", StartDate ); @@ -400,7 +358,6 @@ int main( int argc, char *argv[] ){ mInfo = Lgm_InitMagInfo( ); - OverRideKp = FALSE; if ( !strcmp( ExtModel, "T87" ) ){ mInfo->Bfield = Lgm_B_T87; } else if ( !strcmp( ExtModel, "CDIP" ) ){ @@ -409,31 +366,9 @@ int main( int argc, char *argv[] ){ mInfo->Bfield = Lgm_B_edip; } else if ( !strcmp( ExtModel, "IGRF" ) ){ mInfo->Bfield = Lgm_B_igrf; - } else if ( !strcmp( ExtModel, "TS04" ) ){ - mInfo->Bfield = Lgm_B_TS04; - } else if ( !strcmp( ExtModel, "OP77Q" ) ){ - mInfo->Bfield = Lgm_B_OP77; - } else if ( !strcmp( ExtModel, "OP77" ) ){ - mInfo->Bfield = Lgm_B_OP77; - } else if ( !strcmp( ExtModel, "T89Q" ) ){ - mInfo->Bfield = Lgm_B_T89c; - T89Q_Kp = 2; - OverRideKp = TRUE; - } else if ( !strcmp( ExtModel, "T89D" ) ){ - mInfo->Bfield = Lgm_B_T89c; - } else if ( !strcmp( ExtModel, "T96" ) ){ - mInfo->Bfield = Lgm_B_T96; - } else if ( !strcmp( ExtModel, "TS04D" ) ){ - mInfo->Bfield = Lgm_B_TS04; - } else if ( !strcmp( ExtModel, "T01S" ) ){ - mInfo->Bfield = Lgm_B_T01S; - } else if ( !strcmp( ExtModel, "T01" ) ){ - mInfo->Bfield = Lgm_B_T01S; - } else if ( !strcmp( ExtModel, "T02" ) ){ - mInfo->Bfield = Lgm_B_T02; } else { //if ( !strcmp( ExtModel, "T89" ) ){ // default - mInfo->Bfield = Lgm_B_T89c; + mInfo->Bfield = Lgm_B_T89; } if ( !strcmp( IntModel, "CDIP" ) ){ @@ -510,7 +445,7 @@ int main( int argc, char *argv[] ){ // Create Base directory if it hasnt been created yet. char *dirc = strdup( OutFile ); BaseDir = dirname(dirc); - sprintf( Command, "mkdir -p %s", BaseDir); retval = system( Command ); + sprintf( Command, "mkdir -p %s", BaseDir); system( Command ); free( dirc ); @@ -525,14 +460,7 @@ int main( int argc, char *argv[] ){ if ( StatError != -1 ) { FileExists = TRUE; - if ( !Force && !AppendMode) { - printf("\n\n\tOutfile already exists (use -F option to force processing): %s\n", OutFile ); - } else if (!AppendMode) { - printf("\n\n\tWarning. Existing Outfile will be overwritten: %s \n", OutFile ); - } else { - printf("\n\n\tExisting Outfile will be appended: %s \n", OutFile ); - } - + printf("\n\n\tOutfile already exists: %s\n", OutFile ); if ( StatBuf.st_size < 1000LL ){ printf("\t File size: %lld B\n", (long long)StatBuf.st_size ); } else if ( StatBuf.st_size < 1000000LL ){ @@ -546,377 +474,184 @@ int main( int argc, char *argv[] ){ printf("\t Last file access: %s", ctime(&StatBuf.st_atime)); printf("\tLast file modification: %s", ctime(&StatBuf.st_mtime)); - /* - * If OutFile exists, check to see if it is readable. - */ - if ( !H5Fis_hdf5( OutFile ) ) { - printf("\t Outfile Not Readable: %s. Forcing regeneration of file.\n\n\n", OutFile ); - FileExists = FALSE; - } - } - InFileExists = ( (StatError = stat( InFile, &StatBuf )) != -1 ) ? TRUE : FALSE; /* * Read in a combined Flux/MagEphem HDF5 File */ if ( InFileExists ) { - fromHDF = 0; - if (H5Fis_hdf5( InFile )){ - fromHDF = 1; - // Read the InFile - file = H5Fopen( InFile, H5F_ACC_RDONLY, H5P_DEFAULT ); - - //Read ISO time - IsoTimes = Get_StringDataset_1D( file, "/Epoch", dims); - - // Read GSM and Lstar position - Position = Get_DoubleDataset_2D( file, "/Ephemeris/GSM", dims); - MagEphem_Lstar = Get_DoubleDataset_2D( file, "/Lstar", dims); - - //Read pitch angles for input flux - MagEphem_Alpha = Get_DoubleDataset_1D( file, "/Lstar_Alpha", dims); - MagEphem_nAlpha = dims[0]; - - //Read flux array, pitch angle and energies - Flux_Alpha = Get_DoubleDataset_1D( file, "/PA", dims); - Flux_nAlpha = dims[0]; - Flux_Energy = Get_DoubleDataset_1D( file, "/Energy", dims); - Flux_nEnergy = dims[0]; - J = Get_DoubleDataset_3D( file, "/Flux", dims); - nTimes = dims[0]; - if (Flux_nEnergy != dims[2]) { - printf("Dimensions of input flux array are incorrectly ordered! Exiting.\n"); - exit(-1); - } - status = H5Fclose( file ); - } - else { - - /* - * Read CDF file - */ - cdf_status = CDFopenCDF( InFile, &id ); - if ( cdf_status != CDF_OK ) StatusHandler( cdf_status ); - - /* - * Get FEDU variable. - */ - i = CDFgetVarNum( id, "FEDU"); - CDFinquirezVar( id, i, varName, &dataType, &numElems, &numDims, dimSizes, &recVary, dimVarys ); - if ( cdf_status != CDF_OK ) StatusHandler( cdf_status ); - cdf_status = CDFgetzVarNumRecsWritten( id, i, &numRecs ); - if (cdf_status != CDF_OK) StatusHandler( cdf_status ); - - Ni = numRecs; - Nj = dimSizes[0]; - Nk = dimSizes[1]; - printf("FEDU dimensions [time][alpha][E]: %d %d %d\n", Ni, Nj, Nk ); - - LGM_ARRAY_3D( FEDU, Ni, Nj, Nk, double ); - cdf_status = CDFgetzVarAllRecordsByVarID( id, i, &FEDU[0][0][0] ); - if (cdf_status != CDF_OK) StatusHandler( cdf_status ); - - nTimes = Ni; - Flux_nAlpha = (int)(Nj/2)+1; // assume an odd number like 17. Then 17/2+1 is 9 - //Flux_nEnergy = Nk-1; // drop last integral channel #Integral channel shouldn't be in FEDU variable# - Flux_nEnergy = (arguments.nchannels != 0) ? arguments.nchannels : Nk-1; //Nk-1 used for compatibility with prev revs - printf("J dimensions [time][alpha][E]: %d %d %d\n", Ni, Flux_nAlpha, Flux_nEnergy ); - LGM_ARRAY_3D( J, Ni, Flux_nAlpha, Flux_nEnergy, double ); - /* - * Copy over array. But these arrays go 0-180 in PA. So only use half of the PA range. - */ - for (i=0; i PSD - f2p = Lgm_F2P_CreateFluxToPsd(1); - if (fitMaxw==0) { - f2p->FitType = LGM_F2P_MAXWELLIAN; - f2p->nMaxwellians = numMaxw; - } else { - f2p->FitType = LGM_F2P_SPLINE; - } - f2p->Extrapolate = 1; - f2p->DumpDiagnostics = 0; + LstarDims[0] = nTimes; LstarDims[1] = nK; + LstarSlabSize[0] = 1; LstarSlabSize[1] = nK; + space = H5Screate_simple( 2, LstarDims, NULL ); // rank 2 + LstarDataSet = H5Dcreate( file, "Lstar", H5T_NATIVE_DOUBLE, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); + status = H5Sclose( space ); - IsoTimeStringToDateTime( IsoTimes[k], &d, c ); - printf("\tDate/Time: %s\n", &IsoTimes[k][0] ); - Lgm_Set_Coord_Transforms( d.Date, d.Time, c ); - Lgm_Doy( d.Date, &cYear, &cMonth, &cDay, &cDoy); - cJD = Lgm_JD( cYear, cMonth, cDay, d.Time, LGM_TIME_SYS_UTC, c ); + TimeDims[0] = nTimes; + space = H5Screate_simple( 1, TimeDims, NULL ); // rank 1 + hid_t atype = H5Tcopy (H5T_C_S1); + status = H5Tset_size( atype, strlen(IsoTimes[0]) ); + status = H5Tset_strpad( atype, H5T_STR_NULLPAD ); + status = H5Tset_cset( atype, H5T_CSET_ASCII ); + TimeDataSet = H5Dcreate( file, "IsoTime", atype, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); + status = H5Sclose( space ); - // Determine whether time has been processed - if ( !Force && AppendMode && FileExists ) { - // Assume not processed - AppendFlag = 1; - // Loop through all times - for(iTime=0; iTime PSD + f2p = Lgm_F2P_CreateFluxToPsd(1); + f2p->Extrapolate = 3; - } + IsoTimeStringToDateTime( IsoTimes[k], &d, c ); + printf("\t\tDate/Time: %s\n", IsoTimes[k] ); + Lgm_Set_Coord_Transforms( d.Date, d.Time, c ); + Lgm_Doy( d.Date, &cYear, &cMonth, &cDay, &cDoy); + cJD = Lgm_JD( cYear, cMonth, cDay, d.Time, LGM_TIME_SYS_UTC, c ); -/* // interp the GSM position to this time. IS THIS CORRECT? v.x = GSM[k][0]; v.y = GSM[k][1]; v.z = GSM[k][2]; - printf("\tS/C GSM Position: [ %g, %g, %g ] Re\n", v.x, v.y, v.z ); + printf("\t\tv_gsm = %g %g %g\n", v.x, v.y, v.z ); Lgm_F2P_SetDateTimeAndPos( &d, &v, f2p ); -*/ - - if ( Position[k][0] > LGM_FILL_VALUE ) { - if (fromHDF == 1) { - v.x = Position[k][0]; v.y = Position[k][1]; v.z = Position[k][2]; - } else { //FIXME: Kluge to make CDF and HDF5 do the same... - v_geo.x = Position[k][0]/Re; v_geo.y = Position[k][1]/Re; v_geo.z = Position[k][2]/Re; - Lgm_Convert_Coords( &v_geo, &v, GEO_TO_GSM, c ); - } - printf("\tS/C GSM Position: [ %g, %g, %g ] Re\n", v.x, v.y, v.z ); - - // We need to compute the AlphaOfK array. - Lgm_Make_UTC( d.Date, d.Time, &UTC_DateTime, c ); - - if ( FixModelDateTime ) { - Lgm_F2P_SetDateTimeAndPos( &ModelDateTime, &v, f2p ); - Lgm_get_QinDenton_at_JD( ModelDateTime.JD, &QinDen, 1, 1 ); - Lgm_set_QinDenton( &QinDen, mInfo ); - } else { - Lgm_F2P_SetDateTimeAndPos( &d, &v, f2p ); - Lgm_get_QinDenton_at_JD( d.JD, &QinDen, 1, 1 ); - Lgm_set_QinDenton( &QinDen, mInfo ); - } - - Lgm_Set_Coord_Transforms( d.Date, d.Time, mInfo->c ); - - if ( OverRideKp ) { - mInfo->Kp = T89Q_Kp; - } - - - if (arguments.verbose > 0) { - printf("\tKp: %d\n", mInfo->Kp ); - } - // Add diff. flux data/info to f2p structure. - for (iii=0; iiiAofK[] array. - */ - Lgm_F2P_SetFlux( J_DIFF, Flux_Energy, Flux_nEnergy, Flux_Alpha, Flux_nAlpha, f2p ); - - - - // Compute Phase Space Density at the constant Mu's and K's - mInfo->UseInterpRoutines = TRUE; - Lgm_F2P_GetPsdAtConstMusAndKs( Mu, nMu, K, nK, mInfo, f2p ); + // We need to compute the AlphaOfK array. +// Lgm_Make_UTC( d->Date, d->Time, &UTC_DateTime, c ); + + Lgm_get_QinDenton_at_JD( d.JD, &QinDen, 0 ); + Lgm_set_QinDenton( &QinDen, mInfo ); + Lgm_Set_Coord_Transforms( d.Date, d.Time, mInfo->c ); + Lgm_Setup_AlphaOfK( &d, &v, mInfo ); + #pragma omp parallel private(mInfo2) + #pragma omp for schedule(dynamic, 1) + for ( jjj=0; jjj= 2) { - printf("\tPSD Array (K->Columns, Mu->rows):\n"); - for ( iii=0; iiiPSD_MK[iii][jjj]); - } - printf("]\n"); - } - printf("\n\n"); - } - /* - * Compute the PsdLstar arrays. We already have the Lstar - * values that were computed by MagEphem. But these are not - * at the PAs (i.e. Ks) that we need them to be at. So lets - * interpolate the MagEphem arrays to the Ks that we need. - */ - //int kkk; - for (kk=0; kkAofK[kk], &PsdLstar[kk] ); - AlphaOfK[kk] = ( f2p->AofK[kk] > 0.0 ) ? f2p->AofK[kk] : LGM_FILL_VALUE; -//printf("f2p->AofK[%d] = %g\n", kk, f2p->AofK[kk] ); - //for(kkk=0; kkk< MagEphem_nAlpha; ++kkk){ - //printf("MagEphem_Alpha[%d], MagEphem_Lstar[%d][%d] = %g %g\n", kkk, k, kkk, MagEphem_Alpha[kkk], MagEphem_Lstar[k][kkk] ); - //} - //printf("******** f2p->AofK[%d], PsdLstar[%d] = %g %g\n", kk, f2p->AofK[kk], kk, PsdLstar[kk] ); + // Add diff. flux data/info to f2p structure. + for (iii=0; iiiPSD_MK); - + // Compute Phase Space Density at the constant Mu's and K's + Lgm_F2P_GetPsdAtConstMusAndKs( Mu, nMu, K, nK, f2p ); - } else { - for (kk=0; kkPSD_MK[iii][jjj]); } - - // Write PSD FILL VALS. - double **PSD_MK_FILL; - LGM_ARRAY_2D( PSD_MK_FILL, nMu, nK, double ); - for ( iii=0; iiiPSD_MK[0][0] ); + status = H5Sclose(space); - ++H5_nT; Lgm_F2P_FreeFluxToPsd( f2p ); } + + status = H5Sclose( PsdMemSpace ); + status = H5Dclose( PsdDataSet ); + status = H5Sclose( LstarMemSpace ); + status = H5Dclose( LstarDataSet ); + status = H5Sclose( TimeMemSpace ); + status = H5Dclose( TimeDataSet ); status = H5Fclose( file ); @@ -926,13 +661,9 @@ int main( int argc, char *argv[] ){ printf("\t\tOutput file already exists: %s \n", OutFile ); } - if ( !Force && AppendMode && FileExists ) { - LGM_ARRAY_2D_FREE( ProcessedTime ); - } + LGM_ARRAY_2D_FREE( IsoTimes ); - LGM_ARRAY_1D_FREE( Epoch ); - LGM_ARRAY_2D_FREE( Position ); -// LGM_ARRAY_2D_FREE( GSM ); + LGM_ARRAY_2D_FREE( GSM ); LGM_ARRAY_2D_FREE( MagEphem_Lstar ); LGM_ARRAY_1D_FREE( MagEphem_Alpha ); LGM_ARRAY_1D_FREE( Flux_Alpha ); @@ -964,6 +695,7 @@ int main( int argc, char *argv[] ){ Lgm_destroy_eop( e ); + return(0); } @@ -1019,14 +751,14 @@ void InterpArr( double *xa, double *ya, int n, double x, double *y ) { xa2 = (double *)calloc( n, sizeof(double) ); ya2 = (double *)calloc( n, sizeof(double) ); - + for (i=0; i -#include #include #include #include @@ -9,14 +8,14 @@ #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include void StringSplit( char *Str, char *StrArray[], int len, int *n ); @@ -42,6 +41,7 @@ static char doc[] = "\nComputes magnetic ephemerii of S/C from input file that c #define nArgs 2 static char ArgsDoc[] = "InFile OutFile"; + /* * Description of options accepted. The fields are as follows; * @@ -57,7 +57,6 @@ static struct argp_option Options[] = { {"IntModel", 'i', "internal_model", 0, "Internal Magnetic Field Model to use. Default is IGRF." }, {"ExtModel", 'e', "external_model", 0, "External Magnetic Field Model to use. Default is T89." }, {"Birds", 'b', "\"bird1, bird2, etc\"", 0, "Birds (sats) to use. E.g., \"LANL-02A, 1989-046, POLAR\"." }, - {"BirdsPath", 'B', "\"path\"", 0, "Path for directory containing Birds (sats) subdirectories. Required if you have wildcards in a satellite name." }, {"PitchAngles", 'p', "\"start_pa, end_pa, npa\"", 0, "Pitch angles to compute. Default is \"5.0, 90, 18\"." }, {"FootPointHeight", 'f', "height", 0, "Footpoint height in km. Default is 100km." }, {"Quality", 'q', "quality", 0, "Quality to use for L* calculations. Default is 3." }, @@ -68,8 +67,7 @@ static struct argp_option Options[] = { {"Colorize", 'c', 0, 0, "Colorize output" }, {"Force", 'F', 0, 0, "Overwrite output file even if it already exists" }, {"Coords", 'C', "coord_system", 0, "Coordinate system used in the input file. Can be: LATLONRAD, SM, GSM, GEI2000 or GSE. Default is LATLONRAD." }, - {"verbose", 'v', "verbosity", 0, "Produce verbose output" }, - {"visualize", 'V', 0, 0, "Produce input file for ViewDriftShell visualizer" }, + {"verbose", 'v', 0, OPTION_ARG_OPTIONAL, "Produce verbose output" }, {"silent", 's', 0, OPTION_ARG_OPTIONAL | OPTION_ALIAS }, { 0 } }; @@ -78,7 +76,6 @@ struct Arguments { char *args[ nArgs ]; /* START_PA END_PA PA_INC */ int silent; int verbose; - int visualize; double StartPA; double EndPA; @@ -97,7 +94,6 @@ struct Arguments { int UseEop; char Birds[4096]; - char BirdsPath[4096]; long int StartDate; long int EndDate; }; @@ -110,15 +106,9 @@ static error_t parse_opt (int key, char *arg, struct argp_state *state) { know is a pointer to our arguments structure. */ struct Arguments *arguments = state->input; switch( key ) { - case 'a': // Append - arguments->Append = 1; - break; case 'b': // Birds strncpy( arguments->Birds, arg, 4095 ); break; - case 'B': // BirdsPath - strncpy( arguments->BirdsPath, arg, 4095 ); - break; case 'S': // start date sscanf( arg, "%ld", &arguments->StartDate ); break; @@ -153,10 +143,7 @@ static error_t parse_opt (int key, char *arg, struct argp_state *state) { arguments->silent = 1; break; case 'v': - arguments->verbose = atoi( arg ); - break; - case 'V': - arguments->visualize = 1; + arguments->verbose = 1; break; case ARGP_KEY_ARG: if (state->arg_num >= nArgs) { @@ -189,10 +176,8 @@ static struct argp argp = { Options, parse_opt, ArgsDoc, doc }; int main( int argc, char *argv[] ){ struct Arguments arguments; - glob_t globbuf; - int glob_n; Lgm_CTrans *c = Lgm_init_ctrans( 0 ); - Lgm_Vector Ugsm, U, Rgeo, W; + Lgm_Vector Ugsm, U; Lgm_DateTime UTC; Lgm_Eop *e = Lgm_init_eop( 0 ); Lgm_EopOne eop; @@ -204,54 +189,38 @@ int main( int argc, char *argv[] ){ char IntModel[20], ExtModel[20], CoordSystem[80], Line[5000]; int AppendMode, UseEop, Colorize, Force; FILE *fp_in, *fp_MagEphem; - int nBirds, nBirdsTmp, iBird; - int GotBirdsPath; - char **Birds, **BirdsTmp, Bird[80]; + int nBirds, iBird; + char **Birds, Bird[80]; double Inc, Alpha[1000], FootpointHeight, GeoLat, GeoLon, GeoRad; int nAlpha, Quality; - long int StartDate, EndDate, Date __attribute__((unused)); + long int StartDate, EndDate, Date; int sYear, sMonth, sDay, sDoy, eYear, eMonth, eDay, eDoy, Year, Month, Day; double sJD, eJD, JD, Time; Lgm_MagEphemInfo *MagEphemInfo; - Lgm_MagEphemData *med; Lgm_QinDentonOne p; hid_t file; hid_t space; hid_t atype; hid_t DataSet, MemSpace; - herr_t status __attribute__((unused)); + herr_t status; hsize_t Dims[4], Offset[4], SlabSize[4]; int iT; char **H5_IsoTimes; + double *H5_JD; double UGSM_ARR[3]; + Lgm_Vector *H5_Ugsm; int H5_nT; + int H5_nAlpha; double *H5_Alpha; double **H5_Lstar; double **H5_K; - double pp, rg, cl, T, vel, Beta, Beta2, s, p2c2, E, Ek, Bmin_mag, Bfn_mag, Bfs_mag, Bsc_mag; - double GeodLat, GeodLong, GeodHeight, MLAT, MLON, MLT, R; - Lgm_Vector Bsc_gsm, Bvec, Bvec2, badvec; - double *ProcessedUTC = NULL; - int iTime; - int nTimes = 0; - int AppendFlag, useTS07, staticModel; - - //Set number of elements in MagEphemData to 86401 (N seconds in day +1) as max number of records - int NNN = 86401; - med = Lgm_InitMagEphemData( NNN, 80 ); - - //Set dummy vars to fill apogee/perigee stuff so it doesn't break in HDF5 versions <1.8.7 - badvec.x = -999; - badvec.y = -999; - badvec.z = -999; - med->H5_nAscend = 1; - med->H5_nApogee = 1; - med->H5_nPerigee = 1; - strcpy(&med->H5_Perigee_IsoTimes[0][0], "1899-01-01T00:00:00Z"); - strcpy(&med->H5_Apogee_IsoTimes[0][0], "1899-01-01T00:00:00Z"); - strcpy(&med->H5_Ascend_IsoTimes[0][0], "1899-01-01T00:00:00Z"); + // kludge. + LGM_ARRAY_2D( H5_IsoTimes, 2000, 80, char ); + LGM_ARRAY_1D( H5_JD, 2000, double ); + LGM_ARRAY_1D( H5_Ugsm, 2000, Lgm_Vector ); + /* * Default option values. @@ -261,7 +230,6 @@ int main( int argc, char *argv[] ){ arguments.nPA = 18; // 18 pitch angles arguments.silent = 0; arguments.verbose = 0; - arguments.visualize = 0; arguments.Quality = 3; arguments.Colorize = 0; arguments.Force = 0; @@ -271,25 +239,24 @@ int main( int argc, char *argv[] ){ arguments.EndDate = -1; arguments.FootPointHeight = 100.0; // km strcpy( arguments.IntModel, "IGRF" ); - strcpy( arguments.ExtModel, "T89c" ); + strcpy( arguments.ExtModel, "T89" ); strcpy( arguments.CoordSystem, "LATLONRAD" ); - arguments.BirdsPath[0] = '\0'; + /* * Parse CmdLine arguments and options */ argp_parse (&argp, argc, argv, 0, 0, &arguments); - if (arguments.silent) { - arguments.verbose = 0; //silent flag overrides verbosity setting - } + /* * Define pitch angles to use. */ nAlpha = arguments.nPA; - Inc = ( nAlpha > 1 ) ? (arguments.EndPA - arguments.StartPA)/(double)(nAlpha-1) : 0.0; + Inc = (arguments.EndPA - arguments.StartPA)/(double)(nAlpha-1); for (i=0; i 0)&&(EndDate > 0) ){ + printf( "\t StartDate: %ld\n", StartDate ); + printf( "\t EndDate: %ld\n", EndDate ); + } - for ( glob_n=0; glob_n 1 ){ + printf( "\t Birds:" ); + for (iBird=0; iBird 0 ){ MagEphemInfo = Lgm_InitMagEphemInfo(0, nAlpha); } else { @@ -371,55 +334,24 @@ int main( int argc, char *argv[] ){ // Settings for Lstar calcs - Lgm_SetLstarTolerances(Quality, 24, MagEphemInfo->LstarInfo); + MagEphemInfo->LstarQuality = Quality; MagEphemInfo->SaveShellLines = TRUE; MagEphemInfo->LstarInfo->LSimpleMax = 10.0; - MagEphemInfo->LstarInfo->VerbosityLevel = arguments.verbose; + MagEphemInfo->LstarInfo->VerbosityLevel = 0; MagEphemInfo->LstarInfo->mInfo->VerbosityLevel = 0; MagEphemInfo->LstarInfo->mInfo->Lgm_LossConeHeight = FootpointHeight; - staticModel = FALSE; - useTS07 = FALSE; if ( !strcmp( ExtModel, "T87" ) ){ MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_T87; } else if ( !strcmp( ExtModel, "CDIP" ) ){ MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_cdip; - staticModel = TRUE; } else if ( !strcmp( ExtModel, "EDIP" ) ){ MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_edip; - staticModel = TRUE; - } else if ( !strcmp( ExtModel, "DUNGEY" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_Dungey; - MagEphemInfo->LstarInfo->mInfo->InternalModel = LGM_DUNGEY; - strcpy(IntModel, "DUNGEY"); - staticModel = TRUE; } else if ( !strcmp( ExtModel, "IGRF" ) ){ MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_igrf; - staticModel = TRUE; - } else if ( !strcmp( ExtModel, "TS04" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_TS04; - } else if ( !strcmp( ExtModel, "TS04D" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_TS04; - } else if ( !strcmp( ExtModel, "T89" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_T89; - } else if ( !strcmp( ExtModel, "T89c" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_T89c; - } else if ( !strcmp( ExtModel, "T96" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_T96; - } else if ( !strcmp( ExtModel, "T01S" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_T01S; - } else if ( !strcmp( ExtModel, "T02" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_T02; - } else if ( !strcmp( ExtModel, "OP77" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_OP77; - staticModel = TRUE; - } else if ( !strcmp( ExtModel, "TS07" ) ){ - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_TS07; - useTS07 = TRUE; } else { //if ( !strcmp( ExtModel, "T89" ) ){ // default - strcpy(ExtModel, "T89c"); - MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_T89c; + MagEphemInfo->LstarInfo->mInfo->Bfield = Lgm_B_T89; } if ( !strcmp( IntModel, "CDIP" ) ){ @@ -431,52 +363,25 @@ int main( int argc, char *argv[] ){ MagEphemInfo->LstarInfo->mInfo->InternalModel = LGM_IGRF; } + + /* - * Print summary of our options + * Set pitch angles in MagEphemInfo structure */ - if ( !arguments.silent ) { - printf("\n\n"); - printf( "\t Program/Version: %s\n", argp_program_version ); - printf( "\t Bug Reports To: %s\n", argp_program_bug_address ); - printf( "\t Input File: %s\n", InputFilename ); - printf( "\t Output File: %s\n", OutputFilename ); - printf( "\t Input Coord System: %s\n", CoordSystem ); - printf( "\t Number of Pitch Angles: %d\n", nAlpha ); - printf( "\t Pitch Angles [Degrees]:" ); - for (i=0; i 0)&&(EndDate > 0) ){ - printf( "\t StartDate: %ld\n", StartDate ); - printf( "\t EndDate: %ld\n", EndDate ); - } - - if ( nBirds > 1 ){ - printf( "\t Birds:" ); - for (iBird=0; iBirdnAlpha = nAlpha; + LGM_ARRAY_1D( H5_Alpha, nAlpha, double ); + H5_nAlpha = nAlpha; + for (i=0; iAlpha[i] = Alpha[i]; + H5_Alpha[i] = Alpha[i]; } + LGM_ARRAY_2D( H5_Lstar, 2000, nAlpha, double ); + LGM_ARRAY_2D( H5_K, 2000, nAlpha, double ); + int SubstituteVars = TRUE; if ( (StartDate > 0)&&(EndDate > 0) ){ - printf("StartDate = %ld\n", StartDate); Lgm_Doy( StartDate, &sYear, &sMonth, &sDay, &sDoy); sJD = Lgm_JD( sYear, sMonth, sDay, 12.0, LGM_TIME_SYS_UTC, c ); @@ -490,33 +395,11 @@ int main( int argc, char *argv[] ){ SubstituteVars = FALSE; } - char *BaseDir, NewStr[2048], Str[24], Command[4096]; char *OutFile = (char *)calloc( 2056, sizeof( char ) ); char *HdfOutFile = (char *)calloc( 2056, sizeof( char ) ); - char *InFileTmp = (char *)calloc( 2056, sizeof( char ) ); char *InFile = (char *)calloc( 2056, sizeof( char ) ); - - - - /* - * Set pitch angles in MagEphemInfo structure - */ - MagEphemInfo->nAlpha = nAlpha; - med->H5_nAlpha = nAlpha; - for (i=0; iAlpha[i] = Alpha[i]; - med->H5_Alpha[i] = Alpha[i]; - } - - - - - - - - for ( JD = sJD; JD <= eJD; JD += 1.0 ) { Date = Lgm_JD_to_Date( JD, &Year, &Month, &Day, &Time ); @@ -550,7 +433,8 @@ int main( int argc, char *argv[] ){ } sprintf( HdfOutFile, "%s.h5", OutFile ); - strcat( OutFile, ".txt" ); + + if ( SubstituteVars ) { printf( "\n\n Processing Date: %4d-%02d-%02d Bird: %s\n", Year, Month, Day, Bird ); @@ -581,12 +465,10 @@ int main( int argc, char *argv[] ){ if ( StatError != -1 ) { FileExists = TRUE; - if ( !Force && !AppendMode) { + if ( !Force ) { printf("\n\n\tHdfOutfile already exists (use -F option to force processing): %s\n", HdfOutFile ); - } else if (!AppendMode) { - printf("\n\n\tWarning. Existing HdfOutfile will be overwritten: %s \n", HdfOutFile ); } else { - printf("\n\n\tExisting HdfOutfile will be appended: %s \n", HdfOutFile ); + printf("\n\n\tWarning. Existing HdfOutfile will be overwritten: %s \n", HdfOutFile ); } if ( StatBuf.st_size < 1000LL ){ @@ -613,534 +495,304 @@ int main( int argc, char *argv[] ){ } - hid_t file_id=0; - double *xarray, *yarray, *zarray; - char **UTCarray, isHDF5=0; - int idims=0; - - if ( !FileExists || Force || AppendMode ) { - // Check if the file is HDF5 - char *ext; - if (((ext = strrchr(InFile, '.')) != NULL) && (strcmp(ext, ".h5") == 0)) { - isHDF5 = 1; - file_id = H5Fopen(InFile, H5F_ACC_RDONLY, H5P_DEFAULT); - if (file_id < 0) //failed to open - continue; - xarray = Get_DoubleDataset_1D(file_id, "Latitude", Dims); - yarray = Get_DoubleDataset_1D(file_id, "Longitude", Dims); - zarray = Get_DoubleDataset_1D(file_id, "Radius", Dims); - UTCarray = Get_StringDataset_1D(file_id, "UTC", Dims); - } - else if ( (fp_in = fopen( InFile, "r" ) ) == NULL ){ - printf("\tCould not open file %s for reading\n", InFile ); - continue; - } //else { - - printf( "\t Reading from file: %s\n", InFile ); - // Open Mag Ephem file for writing/appending - if ( !Force && AppendMode && FileExists ) { - fp_MagEphem = fopen( OutFile, "a" ); - printf("\t Appending to file: %s\n", OutFile ); - } else { - fp_MagEphem = fopen( OutFile, "w" ); - Lgm_WriteMagEphemHeader( fp_MagEphem, argp_program_version,ExtModel, 999, "FIX ME", 99999, "FIX ME", NULL, 0, NULL, NULL, 0, NULL, NULL,0, NULL, NULL, MagEphemInfo ); - printf("\t Writing to file: %s\n", OutFile ); - } - if ( UseEop ) { - Lgm_read_eop( e );// Read in the EOP vals - } - // Open MagEphem hdf5 file for writing/appending and Create vars - if ( !Force && AppendMode && FileExists ) { - /* Get the time variable from the HDF5 file to know what has already been processed */ - file = H5Fopen( HdfOutFile, H5F_ACC_RDWR, H5P_DEFAULT ); - ProcessedUTC = Get_DoubleDataset_1D( file, "UTC", Dims ); - nTimes = Dims[0]; - } else { - file = H5Fcreate( HdfOutFile, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT ); - Lgm_WriteMagEphemHeaderHdf( file, argp_program_version, ExtModel, 999, "FIX ME", 99999, "FIX ME", "FIX ME", 1, NULL, NULL, 1, NULL, NULL, 1, NULL, NULL, MagEphemInfo, med ); - } + if ( !FileExists || Force ) { - /* Loop over the times/positions given. Here we assume the file contains, Time and 3 columns: X, Y, Z. - * The meaning of the X, Y, Z columns are dependent upon what CoordSystem is set to; - * CoordSystem X Y Z - * ------------------------------------------------------------------ - * LATLONRAD Latitude (Deg.) Longitude (Deg.) Radius (Re) - * SM Xsm Ysm Zsm - */ - med->H5_nT = 0; - while (1) { - if (isHDF5) { - if (idims >= Dims[0]) - break; - X = xarray[idims]; - Y = yarray[idims]; - Z = zarray[idims]; - snprintf(IsoTimeString, sizeof(IsoTimeString), "%s", UTCarray[idims]); - idims++; - } - else { - if (fgets( Line, 4096, fp_in ) == NULL) - break; - if (Line[0] == '#') - continue; - sscanf(Line, "%s %lf %lf %lf", IsoTimeString, &X, &Y, &Z ); - } + /* + * Open input file for reading + */ + if ( (fp_in = fopen( InFile, "r" ) ) == NULL ){ - // convert ISO time to DateTime - IsoTimeStringToDateTime( IsoTimeString, &UTC, c ); + printf("\tCould not open file %s for reading\n", InFile ); - // Determine whether time has been processed - if ( !Force && AppendMode && FileExists ) {// Assume not processed - AppendFlag = 1; - for(iTime=0; iTimeH5_nT++; - continue; - } - } + } else { - if ( UseEop ) { - // Get (interpolate) the EOP vals from the values in the file at the given Julian Date - Lgm_get_eop_at_JD( UTC.JD, &eop, e ); - // Set the EOP vals in the CTrans structure. - Lgm_set_eop( &eop, c ); - } + printf( "\t Reading from file: %s\n", InFile ); - // Set mag model parameters - if ((!useTS07) && (!staticModel)) { - Lgm_get_QinDenton_at_JD( UTC.JD, &p, 1, 1 ); - Lgm_set_QinDenton( &p, MagEphemInfo->LstarInfo->mInfo ); - } - - else if (useTS07){ //only TS07 should get here... - Lgm_Init_TS07( &(MagEphemInfo->LstarInfo->mInfo->TS07_Info) ); - Lgm_SetCoeffs_TS07( UTC.Date, UTC.Time, &(MagEphemInfo->LstarInfo->mInfo->TS07_Info) ); - } - - //static models don't require QD or other coeffs so should fall through this part without reading files... - // Set up the trans matrices - Lgm_Set_Coord_Transforms( UTC.Date, UTC.Time, c ); - - if ( !strcmp( CoordSystem, "LATLONRAD" ) ){ - // Convert GEO->GSM coords. - GeoLat = X*RadPerDeg; GeoLon = Y*RadPerDeg; GeoRad = Z; - U.x = GeoRad*cos(GeoLon)*cos(GeoLat); - U.y = GeoRad*sin(GeoLon)*cos(GeoLat); - U.z = GeoRad*sin(GeoLat); - Lgm_Convert_Coords( &U, &Ugsm, GEO_TO_GSM, c ); - } else if ( !strcmp( CoordSystem, "SM" ) ){ - // Convert SM->GSM coords. - U.x = X; U.y = Y; U.z = Z; - Lgm_Convert_Coords( &U, &Ugsm, SM_TO_GSM, c ); - } else if ( !strcmp( CoordSystem, "GSM" ) ){ - // No conversion needed. - Ugsm.x = X; Ugsm.y = Y; Ugsm.z = Z; - } else if ( !strcmp( CoordSystem, "GEI2000" ) ){ - // Convert GEI2000->GSM coords. - U.x = X; U.y = Y; U.z = Z; - Lgm_Convert_Coords( &U, &Ugsm, GEI2000_TO_GSM, c ); - } else if ( !strcmp( CoordSystem, "GSE" ) ){ - // Convert GEI->GSM coords. - U.x = X; U.y = Y; U.z = Z; - Lgm_Convert_Coords( &U, &Ugsm, GSE_TO_GSM, c ); - } /* - * Compute L*s, Is, Bms, Footprints, etc... - * These quantities are stored in the MagEphemInfo Structure + * Open Mag Ephem file for writing */ - printf("\n\n\t[ %s ]: %s Bird: %s Ugsm: %g %g %g Re\n", ProgramName, IsoTimeString, Bird, Ugsm.x, Ugsm.y, Ugsm.z ); - printf("\t--------------------------------------------------------------------------------------------------\n"); - Lgm_ComputeLstarVersusPA( UTC.Date, UTC.Time, &Ugsm, nAlpha, Alpha, Colorize, MagEphemInfo ); - Lgm_WriteMagEphemData( fp_MagEphem, IntModel, ExtModel, MagEphemInfo->LstarInfo->mInfo->fKp, MagEphemInfo->LstarInfo->mInfo->Dst, MagEphemInfo ); - - if (( nAlpha > 0 ) && (arguments.visualize)) { - WriteMagEphemInfoStruct( "test.dat", nAlpha, MagEphemInfo ); - } - - // Fill arrays for dumping out as HDF5 files - strcpy( med->H5_IsoTimes[ med->H5_nT ], IsoTimeString ); - strcpy( med->H5_IntModel[ med->H5_nT ], IntModel ); - strcpy( med->H5_ExtModel[ med->H5_nT ], ExtModel ); - switch ( MagEphemInfo->FieldLineType ) { - case LGM_OPEN_IMF: - sprintf( med->H5_FieldLineType[ med->H5_nT ], "%s", "LGM_OPEN_IMF" ); // FL Type - break; - case LGM_CLOSED: - sprintf( med->H5_FieldLineType[ med->H5_nT ], "%s", "LGM_CLOSED" ); // FL Type - break; - case LGM_OPEN_N_LOBE: - sprintf( med->H5_FieldLineType[ med->H5_nT ], "%s", "LGM_OPEN_N_LOBE" ); // FL Type - break; - case LGM_OPEN_S_LOBE: - sprintf( med->H5_FieldLineType[ med->H5_nT ], "%s", "LGM_OPEN_S_LOBE" ); // FL Type - break; - case LGM_INSIDE_EARTH: - sprintf( med->H5_FieldLineType[ med->H5_nT ], "%s", "LGM_INSIDE_EARTH" ); // FL Type - break; - case LGM_TARGET_HEIGHT_UNREACHABLE: - sprintf( med->H5_FieldLineType[ med->H5_nT ], "%s", "LGM_TARGET_HEIGHT_UNREACHABLE" ); // FL Type - break; - default: - sprintf( med->H5_FieldLineType[ med->H5_nT ], "%s", "UNKNOWN FIELD TYPE" ); // FL Type - break; - } - med->H5_Date[ med->H5_nT ] = UTC.Date; - med->H5_Doy[ med->H5_nT ] = UTC.Doy; - med->H5_UTC[ med->H5_nT ] = UTC.Time; - med->H5_JD[ med->H5_nT ] = UTC.JD; - med->H5_InOut[ med->H5_nT ] = MagEphemInfo->InOut; - med->H5_OrbitNumber[ med->H5_nT ] = MagEphemInfo->OrbitNumber; - med->H5_GpsTime[ med->H5_nT ] = Lgm_UTC_to_GpsSeconds( &UTC, c ); - med->H5_TiltAngle[ med->H5_nT ] = c->psi*DegPerRad; - - med->H5_Rgsm[ med->H5_nT ][0] = Ugsm.x; - med->H5_Rgsm[ med->H5_nT ][1] = Ugsm.y; - med->H5_Rgsm[ med->H5_nT ][2] = Ugsm.z; - - Lgm_Set_Coord_Transforms( UTC.Date, UTC.Time, c ); - Lgm_Convert_Coords( &Ugsm, &Rgeo, GSM_TO_GEO, c ); Lgm_VecToArr( &Rgeo, &med->H5_Rgeo[ med->H5_nT ][0] ); - Lgm_Convert_Coords( &Ugsm, &W, GSM_TO_SM, c ); Lgm_VecToArr( &W, &med->H5_Rsm[ med->H5_nT ][0] ); - Lgm_Convert_Coords( &Ugsm, &W, GSM_TO_GEI2000, c ); Lgm_VecToArr( &W, &med->H5_Rgei[ med->H5_nT ][0] ); - Lgm_Convert_Coords( &Ugsm, &W, GSM_TO_GSE, c ); Lgm_VecToArr( &W, &med->H5_Rgse[ med->H5_nT ][0] ); - - Lgm_WGS84_to_GEOD( &Rgeo, &GeodLat, &GeodLong, &GeodHeight ); - Lgm_SetArrElements3( &med->H5_Rgeod[ med->H5_nT ][0], GeodLat, GeodLong, GeodHeight ); - Lgm_SetArrElements2( &med->H5_Rgeod_LatLon[ med->H5_nT ][0], GeodLat, GeodLong ); - med->H5_Rgeod_Height[ med->H5_nT ] = GeodHeight; - - Lgm_Convert_Coords( &Ugsm, &W, GSM_TO_CDMAG, c ); - Lgm_CDMAG_to_R_MLAT_MLON_MLT( &W, &R, &MLAT, &MLON, &MLT, c ); - med->H5_CDMAG_MLAT[ med->H5_nT ] = MLAT; - med->H5_CDMAG_MLON[ med->H5_nT ] = MLON; - med->H5_CDMAG_MLT[ med->H5_nT ] = MLT; - med->H5_CDMAG_R[ med->H5_nT ] = R; - - Lgm_Convert_Coords( &Ugsm, &W, GSM_TO_EDMAG, c ); - Lgm_EDMAG_to_R_MLAT_MLON_MLT( &W, &R, &MLAT, &MLON, &MLT, c ); - med->H5_EDMAG_MLAT[ med->H5_nT ] = MLAT; - med->H5_EDMAG_MLON[ med->H5_nT ] = MLON; - med->H5_EDMAG_MLT[ med->H5_nT ] = MLT; - med->H5_EDMAG_R[ med->H5_nT ] = R; - - med->H5_Kp[ med->H5_nT ] = MagEphemInfo->LstarInfo->mInfo->fKp; - med->H5_Dst[ med->H5_nT ] = MagEphemInfo->LstarInfo->mInfo->Dst; - - med->H5_S_sc_to_pfn[ med->H5_nT ] = (MagEphemInfo->Snorth > 0.0) ? MagEphemInfo->Snorth : LGM_FILL_VALUE; - med->H5_S_sc_to_pfs[ med->H5_nT ] = (MagEphemInfo->Ssouth > 0.0) ? MagEphemInfo->Ssouth : LGM_FILL_VALUE; - med->H5_S_pfs_to_Bmin[ med->H5_nT ] = (MagEphemInfo->Smin > 0.0) ? MagEphemInfo->Smin : LGM_FILL_VALUE; - med->H5_S_Bmin_to_sc[ med->H5_nT ] = ((MagEphemInfo->Ssouth>0.0)&&(MagEphemInfo->Smin > 0.0)) ? MagEphemInfo->Ssouth-MagEphemInfo->Smin : LGM_FILL_VALUE; - med->H5_S_total[ med->H5_nT ] = ((MagEphemInfo->Snorth > 0.0)&&(MagEphemInfo->Ssouth > 0.0)) ? MagEphemInfo->Snorth + MagEphemInfo->Ssouth : LGM_FILL_VALUE; - - med->H5_d2B_ds2[ med->H5_nT ] = MagEphemInfo->d2B_ds2; - med->H5_Sb0[ med->H5_nT ] = MagEphemInfo->Sb0; - med->H5_RadiusOfCurv[ med->H5_nT ] = MagEphemInfo->RofC; - - - MagEphemInfo->LstarInfo->mInfo->Bfield( &Ugsm, &Bsc_gsm, MagEphemInfo->LstarInfo->mInfo ); - med->H5_Bsc_gsm[ med->H5_nT ][0] = Bsc_gsm.x; - med->H5_Bsc_gsm[ med->H5_nT ][1] = Bsc_gsm.y; - med->H5_Bsc_gsm[ med->H5_nT ][2] = Bsc_gsm.z; - med->H5_Bsc_gsm[ med->H5_nT ][3] = Lgm_Magnitude( &Bsc_gsm ); - - if ( MagEphemInfo->FieldLineType == LGM_CLOSED ) { - med->H5_Pmin_gsm[ med->H5_nT ][0] = MagEphemInfo->Pmin.x; - med->H5_Pmin_gsm[ med->H5_nT ][1] = MagEphemInfo->Pmin.y; - med->H5_Pmin_gsm[ med->H5_nT ][2] = MagEphemInfo->Pmin.z; - - MagEphemInfo->LstarInfo->mInfo->Bfield( &MagEphemInfo->Pmin, &Bvec, MagEphemInfo->LstarInfo->mInfo ); - Bmin_mag = Lgm_Magnitude( &Bvec ); - med->H5_Bmin_gsm[ med->H5_nT ][0] = Bvec.x; - med->H5_Bmin_gsm[ med->H5_nT ][1] = Bvec.y; - med->H5_Bmin_gsm[ med->H5_nT ][2] = Bvec.z; - med->H5_Bmin_gsm[ med->H5_nT ][3] = Bmin_mag; - - } else { - med->H5_Pmin_gsm[ med->H5_nT ][0] = LGM_FILL_VALUE ; - med->H5_Pmin_gsm[ med->H5_nT ][1] = LGM_FILL_VALUE ; - med->H5_Pmin_gsm[ med->H5_nT ][2] = LGM_FILL_VALUE ; - - med->H5_Bmin_gsm[ med->H5_nT ][0] = LGM_FILL_VALUE ; - med->H5_Bmin_gsm[ med->H5_nT ][1] = LGM_FILL_VALUE ; - med->H5_Bmin_gsm[ med->H5_nT ][2] = LGM_FILL_VALUE ; - med->H5_Bmin_gsm[ med->H5_nT ][3] = LGM_FILL_VALUE ; - Bmin_mag = LGM_FILL_VALUE; - } - - - for (i=0; iH5_Lstar[ med->H5_nT ][i] = MagEphemInfo->Lstar[i]; - med->H5_DriftShellType[ med->H5_nT ][i] = MagEphemInfo->DriftOrbitType[i]; - med->H5_Sb[ med->H5_nT ][i] = MagEphemInfo->Sb[i]; - med->H5_I[ med->H5_nT ][i] = MagEphemInfo->I[i]; - med->H5_Bm[ med->H5_nT ][i] = MagEphemInfo->Bm[i]; + fp_MagEphem = fopen( OutFile, "w" ); + Lgm_WriteMagEphemHeader( fp_MagEphem, 999, "FIX ME", 99999, "FIX ME", NULL, 0, NULL, NULL, 0, NULL, NULL, MagEphemInfo ); + printf("\t Writing to file: %s\n", OutFile ); - Ek = 1.0; // MeV - E = Ek + LGM_Ee0; // total energy, MeV - p2c2 = Ek*(Ek+2.0*LGM_Ee0); // p^2c^2, MeV^2 - Beta2 = p2c2/(E*E); // beta^2 = v^2/c^2 (dimensionless) - Beta = sqrt( Beta2 ); - vel = Beta*LGM_c; // velocity in m/s - vel /= (Re*1000.0); // Re/s - T = ( MagEphemInfo->Sb[i] > 0.0 ) ? 2.0*MagEphemInfo->Sb[i]/vel : LGM_FILL_VALUE; - - pp = sqrt(p2c2)*1.60217646e-13/LGM_c; // mks - rg = sin(MagEphemInfo->Alpha[i]*RadPerDeg)*pp/(LGM_e*Bmin_mag*1e-9); // m. Bmin_mag calced above - - med->H5_Tb[ med->H5_nT ][i] = T; - med->H5_Kappa[ med->H5_nT ][i] = sqrt( MagEphemInfo->RofC*Re*1e3/rg ); - - - if ( (MagEphemInfo->Bm[i]>0.0)&&(MagEphemInfo->I[i]>=0.0) ) { - med->H5_K[ med->H5_nT ][i] = 3.16227766e-3*MagEphemInfo->I[i]*sqrt(MagEphemInfo->Bm[i]); - } else { - med->H5_K[ med->H5_nT ][i] = LGM_FILL_VALUE; - } - if (MagEphemInfo->I[i]>=0.0) { - med->H5_L[ med->H5_nT ][i] = LFromIBmM_McIlwain(MagEphemInfo->I[i], MagEphemInfo->Bm[i], MagEphemInfo->Mused ); - } else { - med->H5_L[ med->H5_nT ][i] = LGM_FILL_VALUE; - } + if ( UseEop ) { + // Read in the EOP vals + Lgm_read_eop( e ); } - /* - * Compute Lsimple - */ - med->H5_Lsimple[ med->H5_nT ] = ( Bmin_mag > 0.0) ? Lgm_Magnitude( &MagEphemInfo->Pmin ) : LGM_FILL_VALUE; /* - * Compute InvLat + * Loop over the times/positions given. Here we assume the file contains, Time and 3 columns: X, Y, Z. + * The meaning of the X, Y, Z columns are dependent upon what CoordSystem is set to; + * + * CoordSystem X Y Z + * ------------------------------------------------------------------ + * LATLONRAD Latitude (Deg.) Longitude (Deg.) Radius (Re) + * SM Xsm Ysm Zsm + * GSM Xsm Ysm Zsm + * GEI2000 Xgsm Ygsm Zgsm + * GSE Xgse Ygse Zgse + * + * Add more as needed.... */ - if (med->H5_Lsimple[ med->H5_nT ] > 0.0) { - med->H5_InvLat[ med->H5_nT ] = DegPerRad*acos(sqrt(1.0/med->H5_Lsimple[ med->H5_nT ])); - } else { - med->H5_InvLat[ med->H5_nT ] = LGM_FILL_VALUE; - } + H5_nT = 0; + while ( fgets( Line, 4096, fp_in ) != NULL ) { - /* - * Compute Lm_eq - */ - med->H5_Lm_eq[ med->H5_nT ] = (Bmin_mag > 0.0) ? LFromIBmM_McIlwain( 0.0, Bmin_mag, MagEphemInfo->Mcurr ) : LGM_FILL_VALUE; + if ( Line[0] != '#' ) { - /* - * Compute InvLat_eq - */ - if (med->H5_Lm_eq[ med->H5_nT ] > 0.0) { - med->H5_InvLat_eq[ med->H5_nT ] = DegPerRad*acos(sqrt(1.0/med->H5_Lm_eq[ med->H5_nT ])); - } else { - med->H5_InvLat_eq[ med->H5_nT ] = LGM_FILL_VALUE; - } + sscanf( Line, "%s %lf %lf %lf", IsoTimeString, &X, &Y, &Z ); - /* - * Compute BoverBeq - */ - Bsc_mag = Lgm_Magnitude( &Bsc_gsm ); - med->H5_BoverBeq[ med->H5_nT ] = ( Bmin_mag > 0.0) ? Bsc_mag / Bmin_mag : LGM_FILL_VALUE; + // convert ISO time to DateTime + IsoTimeStringToDateTime( IsoTimeString, &UTC, c ); - /* - * Compute MlatFromBoverBeq - */ - if ( med->H5_BoverBeq[ med->H5_nT ] > 0.0 ) { - s = sqrt( 1.0/med->H5_BoverBeq[ med->H5_nT ] ); - cl = Lgm_CdipMirrorLat( s ); - if ( fabs(cl) <= 1.0 ){ - med->H5_MlatFromBoverBeq[ med->H5_nT ] = DegPerRad*acos( cl ); - if (med->H5_S_Bmin_to_sc[ med->H5_nT ]<0.0) med->H5_MlatFromBoverBeq[ med->H5_nT ] *= -1.0; - } else { - med->H5_MlatFromBoverBeq[ med->H5_nT ] = LGM_FILL_VALUE; - } - } else { - med->H5_MlatFromBoverBeq[ med->H5_nT ] = LGM_FILL_VALUE; - } + if ( UseEop ) { + // Get (interpolate) the EOP vals from the values in the file at the given Julian Date + Lgm_get_eop_at_JD( UTC.JD, &eop, e ); - /* - * Save M values - */ - med->H5_M_used[ med->H5_nT ] = MagEphemInfo->Mused; - med->H5_M_ref[ med->H5_nT ] = MagEphemInfo->Mref; - med->H5_M_igrf[ med->H5_nT ] = MagEphemInfo->Mcurr; + // Set the EOP vals in the CTrans structure. + Lgm_set_eop( &eop, c ); + } + // Set mag model parameters + Lgm_get_QinDenton_at_JD( UTC.JD, &p, 0 ); + Lgm_set_QinDenton( &p, MagEphemInfo->LstarInfo->mInfo ); - if ( (MagEphemInfo->FieldLineType == LGM_CLOSED) || (MagEphemInfo->FieldLineType == LGM_OPEN_N_LOBE) ) { + // Set up the trans matrices + Lgm_Set_Coord_Transforms( UTC.Date, UTC.Time, c ); - /* - * Save northern Footpoint position in different coord systems. - */ - Lgm_VecToArr( &MagEphemInfo->Ellipsoid_Footprint_Pn, med->H5_Pfn_gsm[ med->H5_nT ] ); + if ( !strcmp( CoordSystem, "LATLONRAD" ) ){ + // Convert GEO->GSM coords. + GeoLat = X*RadPerDeg; GeoLon = Y*RadPerDeg; GeoRad = Z; + U.x = GeoRad*cos(GeoLon)*cos(GeoLat); + U.y = GeoRad*sin(GeoLon)*cos(GeoLat); + U.z = GeoRad*sin(GeoLat); + Lgm_Convert_Coords( &U, &Ugsm, GEO_TO_GSM, c ); + } else if ( !strcmp( CoordSystem, "SM" ) ){ + // Convert SM->GSM coords. + U.x = X; U.y = Y; U.z = Z; + Lgm_Convert_Coords( &U, &Ugsm, SM_TO_GSM, c ); + } else if ( !strcmp( CoordSystem, "GSM" ) ){ + // No conversion needed. + Ugsm.x = X; Ugsm.y = Y; Ugsm.z = Z; + } else if ( !strcmp( CoordSystem, "GEI2000" ) ){ + // Convert GEI2000->GSM coords. + U.x = X; U.y = Y; U.z = Z; + Lgm_Convert_Coords( &U, &Ugsm, GEI2000_TO_GSM, c ); + } else if ( !strcmp( CoordSystem, "GSE" ) ){ + // Convert GEI->GSM coords. + U.x = X; U.y = Y; U.z = Z; + Lgm_Convert_Coords( &U, &Ugsm, GSE_TO_GSM, c ); + } - Lgm_Convert_Coords( &MagEphemInfo->Ellipsoid_Footprint_Pn, &W, GSM_TO_GEO, c ); - Lgm_VecToArr( &W, med->H5_Pfn_geo[ med->H5_nT ] ); - Lgm_WGS84_to_GEOD( &W, &GeodLat, &GeodLong, &GeodHeight ); - Lgm_SetArrElements3( med->H5_Pfn_geod[ med->H5_nT ], GeodLat, GeodLong, GeodHeight ); - Lgm_SetArrElements2( med->H5_Pfn_geod_LatLon[ med->H5_nT ], GeodLat, GeodLong ); - med->H5_Pfn_geod_Height[ med->H5_nT ] = GeodHeight; - Lgm_Convert_Coords( &MagEphemInfo->Ellipsoid_Footprint_Pn, &W, GSM_TO_CDMAG, c ); - Lgm_CDMAG_to_R_MLAT_MLON_MLT( &W, &R, &MLAT, &MLON, &MLT, c ); - Lgm_SetArrElements3( med->H5_Pfn_cdmag[ med->H5_nT ], MLAT, MLON, MLT ); - med->H5_Pfn_CD_MLAT[ med->H5_nT ] = MLAT; - med->H5_Pfn_CD_MLON[ med->H5_nT ] = MLON; - med->H5_Pfn_CD_MLT[ med->H5_nT ] = MLT; - Lgm_Convert_Coords( &MagEphemInfo->Ellipsoid_Footprint_Pn, &W, GSM_TO_EDMAG, c ); - Lgm_EDMAG_to_R_MLAT_MLON_MLT( &W, &R, &MLAT, &MLON, &MLT, c ); - Lgm_SetArrElements3( med->H5_Pfn_edmag[ med->H5_nT ], MLAT, MLON, MLT ); - med->H5_Pfn_ED_MLAT[ med->H5_nT ] = MLAT; - med->H5_Pfn_ED_MLON[ med->H5_nT ] = MLON; - med->H5_Pfn_ED_MLT[ med->H5_nT ] = MLT; + /* + * Compute L*s, Is, Bms, Footprints, etc... + * These quantities are stored in the MagEphemInfo Structure + */ + printf("\n\n\t[ %s ]: %s Bird: %s Ugsm: %g %g %g Re\n", ProgramName, IsoTimeString, Bird, Ugsm.x, Ugsm.y, Ugsm.z ); + printf("\t--------------------------------------------------------------------------------------------------\n"); + Lgm_ComputeLstarVersusPA( UTC.Date, UTC.Time, &Ugsm, nAlpha, Alpha, MagEphemInfo->LstarQuality, Colorize, MagEphemInfo ); + Lgm_WriteMagEphemData( fp_MagEphem, IntModel, ExtModel, MagEphemInfo->LstarInfo->mInfo->fKp, MagEphemInfo->LstarInfo->mInfo->Dst, MagEphemInfo ); - /* - * Save northern Footpoint B-field values in different coord systems. - */ - MagEphemInfo->LstarInfo->mInfo->Bfield( &MagEphemInfo->Ellipsoid_Footprint_Pn, &Bvec, MagEphemInfo->LstarInfo->mInfo ); - Lgm_Convert_Coords( &Bvec, &Bvec2, GSM_TO_WGS84, c ); - Lgm_VecToArr( &Bvec, &med->H5_Bfn_gsm[ med->H5_nT ][0] ); med->H5_Bfn_gsm[ med->H5_nT ][3] = Lgm_Magnitude( &Bvec ); - Lgm_VecToArr( &Bvec2, &med->H5_Bfn_geo[ med->H5_nT ][0] ); med->H5_Bfn_geo[ med->H5_nT ][3] = Lgm_Magnitude( &Bvec2 ); + if ( nAlpha > 0 ){ + WriteMagEphemInfoStruct( "test.dat", nAlpha, MagEphemInfo ); + } - /* - * Save northern loss cone. - */ - Bfn_mag = Lgm_Magnitude( &Bvec ); - med->H5_LossConeAngleN[ med->H5_nT ] = asin( sqrt( Bsc_mag/Bfn_mag ) )*DegPerRad; - } else { - Lgm_SetArrVal3( med->H5_Pfn_gsm[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal3( med->H5_Pfn_geo[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal3( med->H5_Pfn_geod[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal2( med->H5_Pfn_geod_LatLon[ med->H5_nT ], LGM_FILL_VALUE ); + // Fill arrays for dumping out as HDF5 files + strcpy( H5_IsoTimes[H5_nT], IsoTimeString ); + H5_JD[H5_nT] = UTC.JD; + H5_Ugsm[H5_nT] = Ugsm; + for (i=0; iLstar[i]; + if (MagEphemInfo->Bm[i]>0.0) { + H5_K[H5_nT][i] = 3.16227766e-3*MagEphemInfo->I[i]*sqrt(MagEphemInfo->Bm[i]); + } else { + H5_K[H5_nT][i] = LGM_FILL_VALUE; + } + } - med->H5_Pfn_geod_Height[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfn_CD_MLAT[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfn_CD_MLON[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfn_CD_MLT[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfn_ED_MLAT[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfn_ED_MLON[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfn_ED_MLT[ med->H5_nT ] = LGM_FILL_VALUE; - Lgm_SetArrVal3( med->H5_Pfn_cdmag[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal3( med->H5_Pfn_edmag[ med->H5_nT ], LGM_FILL_VALUE ); + ++H5_nT; - Lgm_SetArrVal4( med->H5_Bfn_geo[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal4( med->H5_Bfn_gsm[ med->H5_nT ], LGM_FILL_VALUE ); + } - med->H5_LossConeAngleN[ med->H5_nT ] = LGM_FILL_VALUE; } + fclose(fp_in); + fclose(fp_MagEphem); - if ( (MagEphemInfo->FieldLineType == LGM_CLOSED) || (MagEphemInfo->FieldLineType == LGM_OPEN_S_LOBE) ) { - - /* - * Save southern Footpoint position in different coord systems. - */ - Lgm_VecToArr( &MagEphemInfo->Ellipsoid_Footprint_Ps, med->H5_Pfs_gsm[ med->H5_nT ] ); - Lgm_Convert_Coords( &MagEphemInfo->Ellipsoid_Footprint_Ps, &W, GSM_TO_GEO, c ); - Lgm_VecToArr( &W, med->H5_Pfs_geo[ med->H5_nT ] ); - - Lgm_WGS84_to_GEOD( &W, &GeodLat, &GeodLong, &GeodHeight ); - Lgm_SetArrElements3( med->H5_Pfs_geod[ med->H5_nT ], GeodLat, GeodLong, GeodHeight ); - Lgm_SetArrElements2( med->H5_Pfs_geod_LatLon[ med->H5_nT ], GeodLat, GeodLong ); - med->H5_Pfs_geod_Height[ med->H5_nT ] = GeodHeight; - - Lgm_Convert_Coords( &MagEphemInfo->Ellipsoid_Footprint_Ps, &W, GSM_TO_CDMAG, c ); - Lgm_CDMAG_to_R_MLAT_MLON_MLT( &W, &R, &MLAT, &MLON, &MLT, c ); - Lgm_SetArrElements3( med->H5_Pfs_cdmag[ med->H5_nT ], MLAT, MLON, MLT ); - med->H5_Pfs_CD_MLAT[ med->H5_nT ] = MLAT; - med->H5_Pfs_CD_MLON[ med->H5_nT ] = MLON; - med->H5_Pfs_CD_MLT[ med->H5_nT ] = MLT; - - Lgm_Convert_Coords( &MagEphemInfo->Ellipsoid_Footprint_Ps, &W, GSM_TO_EDMAG, c ); - Lgm_EDMAG_to_R_MLAT_MLON_MLT( &W, &R, &MLAT, &MLON, &MLT, c ); - Lgm_SetArrElements3( med->H5_Pfs_edmag[ med->H5_nT ], MLAT, MLON, MLT ); - med->H5_Pfs_ED_MLAT[ med->H5_nT ] = MLAT; - med->H5_Pfs_ED_MLON[ med->H5_nT ] = MLON; - med->H5_Pfs_ED_MLT[ med->H5_nT ] = MLT; - - - /* - * Save southern Footpoint B-field values in different coord systems. - */ - MagEphemInfo->LstarInfo->mInfo->Bfield( &MagEphemInfo->Ellipsoid_Footprint_Ps, &Bvec, MagEphemInfo->LstarInfo->mInfo ); - Lgm_Convert_Coords( &Bvec, &Bvec2, GSM_TO_WGS84, c ); - Lgm_VecToArr( &Bvec, &med->H5_Bfs_gsm[ med->H5_nT ][0] ); med->H5_Bfs_gsm[ med->H5_nT ][3] = Lgm_Magnitude( &Bvec ); - Lgm_VecToArr( &Bvec2, &med->H5_Bfs_geo[ med->H5_nT ][0] ); med->H5_Bfs_geo[ med->H5_nT ][3] = Lgm_Magnitude( &Bvec2 ); - - - /* - * Save southern loss cone. - */ - Bfs_mag = Lgm_Magnitude( &Bvec ); - med->H5_LossConeAngleS[ med->H5_nT ] = asin( sqrt( Bsc_mag/Bfs_mag ) )*DegPerRad; - - - } else { - - Lgm_SetArrVal3( med->H5_Pfs_gsm[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal3( med->H5_Pfs_geo[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal3( med->H5_Pfs_geod[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal2( med->H5_Pfs_geod_LatLon[ med->H5_nT ], LGM_FILL_VALUE ); - - med->H5_Pfs_geod_Height[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfs_CD_MLAT[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfs_CD_MLON[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfs_CD_MLT[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfs_ED_MLAT[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfs_ED_MLON[ med->H5_nT ] = LGM_FILL_VALUE; - med->H5_Pfs_ED_MLT[ med->H5_nT ] = LGM_FILL_VALUE; - - Lgm_SetArrVal3( med->H5_Pfs_cdmag[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal3( med->H5_Pfs_edmag[ med->H5_nT ], LGM_FILL_VALUE ); - - Lgm_SetArrVal4( med->H5_Bfs_geo[ med->H5_nT ], LGM_FILL_VALUE ); - Lgm_SetArrVal4( med->H5_Bfs_gsm[ med->H5_nT ], LGM_FILL_VALUE ); - - med->H5_LossConeAngleS[ med->H5_nT ] = LGM_FILL_VALUE; + // Create HDF5 file + file = H5Fcreate( HdfOutFile, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT ); + // Create IsoTime Dataset + Dims[0] = H5_nT; + space = H5Screate_simple( 1, Dims, NULL ); // rank 1 + atype = H5Tcopy( H5T_C_S1 ); + status = H5Tset_size( atype, strlen(H5_IsoTimes[0]) ); + status = H5Tset_strpad( atype, H5T_STR_NULLPAD ); + status = H5Tset_cset( atype, H5T_CSET_ASCII ); + DataSet = H5Dcreate( file, "IsoTime", atype, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); + status = H5Sclose( space ); + status = H5Dclose( DataSet ); + status = H5Tclose( atype ); + + // Create JD Dataset + Dims[0] = H5_nT; + space = H5Screate_simple( 1, Dims, NULL ); // rank 1 + DataSet = H5Dcreate( file, "JulianDate", H5T_NATIVE_DOUBLE, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); + status = H5Sclose( space ); + status = H5Dclose( DataSet ); + + // Create Ugsm Dataset + Dims[0] = H5_nT; Dims[1] = 3; + space = H5Screate_simple( 2, Dims, NULL ); // rank 2 + DataSet = H5Dcreate( file, "Ugsm", H5T_NATIVE_DOUBLE, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); + status = H5Sclose( space ); + status = H5Dclose( DataSet ); + + // Create Alpha Dataset + Dims[0] = H5_nAlpha; + space = H5Screate_simple( 1, Dims, NULL ); // rank 1 + DataSet = H5Dcreate( file, "Alpha", H5T_NATIVE_DOUBLE, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); + status = H5Sclose( space ); + status = H5Dclose( DataSet ); + + // Create Lstar Dataset + Dims[0] = H5_nT; Dims[1] = H5_nAlpha; + space = H5Screate_simple( 2, Dims, NULL ); // rank 2 + DataSet = H5Dcreate( file, "Lstar", H5T_NATIVE_DOUBLE, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); + status = H5Sclose( space ); + status = H5Dclose( DataSet ); + + // Create K Dataset + Dims[0] = H5_nT; Dims[1] = H5_nAlpha; + space = H5Screate_simple( 2, Dims, NULL ); // rank 2 + DataSet = H5Dcreate( file, "K", H5T_NATIVE_DOUBLE, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); + status = H5Sclose( space ); + status = H5Dclose( DataSet ); + + + + + // Write IsoTime Strings + SlabSize[0] = 1; + DataSet = H5Dopen( file, "IsoTime", H5P_DEFAULT ); + space = H5Dget_space( DataSet ); + MemSpace = H5Screate_simple( 1, SlabSize, NULL ); + atype = H5Tcopy( H5T_C_S1 ); + status = H5Tset_size( atype, strlen(H5_IsoTimes[0]) ); + status = H5Tset_strpad( atype, H5T_STR_NULLPAD ); + status = H5Tset_cset( atype, H5T_CSET_ASCII ); + for ( iT=0; iTH5_nT, med->H5_nT, med ); - ++(med->H5_nT); - - } //end while loop - fclose(fp_in); - fclose(fp_MagEphem); - - H5Fclose( file ); } - if (isHDF5) - H5Fclose(file_id); } // end birds loop } // end JD loop - free( BirdsPath ); - free( Path ); free( OutFile ); - free( InFileTmp ); free( InFile ); Lgm_free_ctrans( c ); Lgm_destroy_eop( e ); Lgm_FreeMagEphemInfo( MagEphemInfo ); - LGM_ARRAY_2D_FREE( BirdsTmp ); LGM_ARRAY_2D_FREE( Birds ); + LGM_ARRAY_2D_FREE( H5_IsoTimes ); + LGM_ARRAY_1D_FREE( H5_JD ); + LGM_ARRAY_1D_FREE( H5_Ugsm ); + LGM_ARRAY_1D_FREE( H5_Alpha ); + LGM_ARRAY_2D_FREE( H5_Lstar ); + LGM_ARRAY_2D_FREE( H5_K ); + + + return(0); } diff --git a/Examples/MagEphem/Makefile b/Examples/MagEphem/Makefile index ac7f1e541..166407778 100644 --- a/Examples/MagEphem/Makefile +++ b/Examples/MagEphem/Makefile @@ -1,21 +1,23 @@ -#CFLAGS = -Wall -O3 -march=opteron -msse2 -mfpmath=sse,387 -ffast-math -CDF_LIBS = -lcdf -L/usr/local/cdf/lib -CDF_INC = -I/usr/local/cdf/include +#CFLAGS = -Wall -O3 -march=opteron -msse2 -mfpmath=sse,387 -ffast-math +FFLAGS = -fno-automatic +SPICE_LIBS = '/home/mgh/SPICE/cspice/lib/cspice.a' +SPICE_INC = '-I/home/mgh/SPICE/cspice/include' +#HDF5_LIBS = '-L/packages/lib/hdf5-1.8.7' +#HDF5_INC = '-I/packages/include/hdf5-1.8' +LIBS = `pkg-config --libs lgm` +CFLAGS = `pkg-config --cflags lgm` $(SPICE_INC) +CC = gcc -LIBS := `pkg-config --libs lgm` $(CDF_LIBS) `pkg-config --libs hdf5 2> /dev/null` -CFLAGS := `pkg-config --cflags lgm` $(CDF_INC) -g `pkg-config --cflags hdf5 2> /dev/null` -CC = gcc -Wno-unused-variable -FILES = MagEphemFromFile -all: $(FILES) DreamAssim FluxToPSD +all : MagEphemFromSpiceKernel --include extra_flags +MagEphemFromFile : Makefile MagEphemFromFile.o + $(CC) $(FILES1) MagEphemFromFile.o $(HDF5_LIBS) $(LIBS) $(CFLAGS) -o MagEphemFromFile + +MagEphemFromSpiceKernel : Makefile MagEphemFromSpiceKernel.o + $(CC) $(FILES1) MagEphemFromSpiceKernel.o $(HDF5_LIBS) $(LIBS) $(CFLAGS) $(SPICE_LIBS) -o MagEphemFromSpiceKernel -extra_flags: - if [[ "${MACHTYPE}" =~ "*darwin*" ]]; then echo "LIBS := -largp -I/opt/local/include -L/opt/local/lib" > extra_flags; echo "CFLAGS := -I/opt/local/include -L/opt/local/lib -largp" >> extra_flags; else echo > extra_flags; fi -$(FILES): %: %.c Makefile - $(CC) $< $(LIBS) $(CFLAGS) -o $@ clean : - rm MagEphemFromFile *.o + rm MagEphemFromFile MagEphemFromSpiceKernel *.o diff --git a/Examples/TLE/Makefile b/Examples/TLE/Makefile index 538a65400..f988fb78c 100644 --- a/Examples/TLE/Makefile +++ b/Examples/TLE/Makefile @@ -8,6 +8,9 @@ FILES1 = all : TwoLineElements TwoLineElementsFromFile NearestTLE Forte_Meteor +Forte_Meteor : Makefile $(FILES1) Forte_Meteor.c + $(CC) $(FILES1) Forte_Meteor.c $(LIBS) -o Forte_Meteor + TwoLineElements : Makefile $(FILES1) TwoLineElements.c $(CC) $(FILES1) TwoLineElements.c $(LIBS) -o TwoLineElements diff --git a/HACKING b/HACKING index eb17fe761..a884d3dc1 100644 --- a/HACKING +++ b/HACKING @@ -4,12 +4,10 @@ Instructions for developers who use the source code repository GIT repository ============== -The source repository can be obtained (read-only) at: +Initial checkout: git clone https://github.com/drsteve/LANLGeoMag.git -For write access, fork the repository and clone from your fork. Further information can be found in the github help. - Then: cd LanlGeoMag @@ -24,8 +22,6 @@ git commit git pull git push -Then send a pull request with your changes. - Prerequisites ============= @@ -130,49 +126,14 @@ to build RPMs. RPMs are not yet working because we still have Ctypesgen ========= The Python wrappers require ctypesgen. For simplicity, we bundle our own -version from https://github.com/olsonse/ctypesgen - -There's a nice discussion at -https://medium.com/@porteneuve/mastering-git-subtrees-943d29a798ec - -If you aren't hacking on the ctypes code itself, there's no need to read -any of this. But if you need to update the bundled ctypes, first set up -the repositories: - -git remote add ctypesgen https://github.com/olsonse/ctypesgen.git +version. Here's how to make that bundle: +svn checkout http://ctypesgen.googlecode.com/svn/trunk/ ctypesgen-read-only +Copy entire contents to Python/ctypesgen in the lanlgeomag directory, and +check them in. We should refer to this license (3-clause BSD) in the +lanlgeomag docs. -To start this process from scratch (i.e. before we had anything pulled in): -git fetch ctypesgen -git read-tree --prefix=Python/ctypesgen/ -u ctypesgen/master - -But to update ctypesgen now that it's been incorporated: -git fetch ctypesgen -git merge -s subtree --squash ctypesgen/master -git rev-parse ctypesgen/master #To get SHA1 -git commit -m "Update ctypesgen to (SHA1)" - -We should refer to this license (3-clause BSD) in the lanlgeomag docs. make dist =========== It seems you need to make with --enable-doxygen-doc on the ./configure cmd line.... - -Unit tests -========== -The unit tests test against the version of the library as built (not -installed). But the data directories are compiled in as at install -time. So you need to do a build of the library with those locations -specified in order to test. The directory layout in the source tree -doesn't match the expected directory layout post-install. Long-term -either there should be configure options/environment variables to -specify every directory separately (at build time or runtime), or the -layout of these directories in the source should match the expected -installed layout. For now we patch up with symlinks. - -make clean -ln -s ./libLanlGeoMag/ LanlGeoMag -./configure --datadir="`pwd`" -make -JPL_EPHEM_PATH="`pwd`/libLanlGeoMag/DE_FILES/" make check -rm ./LanlGeoMag diff --git a/Makefile.am b/Makefile.am index 5e37f2233..3e55b87ca 100644 --- a/Makefile.am +++ b/Makefile.am @@ -9,10 +9,10 @@ if HAVE_PYTHON endif SUBDIRS = libLanlGeoMag . $(MAYBE_TOOLS) $(MAYBE_TESTS) $(MAYBE_PY) -if DX_COND_pdf - MAYBE_PDF = @DX_DOCDIR@/@DX_PROJECT@.pdf - uninst_pdf = $(pdfdir) -endif +# if DX_COND_pdf +# MAYBE_PDF = @DX_DOCDIR@/@DX_PROJECT@_Documentation.pdf +# uninst_pdf = $(pdfdir) +# endif if DX_COND_ps MAYBE_PS = @DX_DOCDIR@/@DX_PROJECT@.ps uninst_ps = $(psdir) @@ -56,8 +56,6 @@ AM_CPPFLAGS = -DDATADIR='"$(datadir)"' if DX_COND_html #and make sure html is build when doing a make all #(for some reason this bit doesn't honor DESTDIR without doing it explicitly) -README: README.md - all-local: @DX_DOCDIR@/html install-data-local: diff --git a/Python/Makefile.am b/Python/Makefile.am index 40e43a1ef..28f8495b4 100644 --- a/Python/Makefile.am +++ b/Python/Makefile.am @@ -8,13 +8,13 @@ HDF5FLAGS = `pkg-config hdf5 --cflags --libs 2>/dev/null` all-local: Lgm_Wrap_gen.py #make generic wrapper at build time Lgm_Wrap_gen.py: $(top_builddir)/libLanlGeoMag/libLanlGeoMag.la $(LGMSRCDIR)/Lgm/*.h - PYTHONPATH=$(srcdir)/ctypesgen:${PYTHONPATH} $(PYTHON) $(srcdir)/ctypesgen/run.py $(HDF5FLAGS) -lLanlGeoMag --no-macro-warnings -o Lgm_Wrap_gen.py --compile-libdir=$(top_builddir)/libLanlGeoMag/.libs --runtime-libdir=RUNTIME_LIBDIR --includedir=$(LGMSRCDIR)/Lgm --includedir=$(LGMSRCDIR) $(LGMSRCDIR)/Lgm/*.h >ctypesgen.log 2>ctypesgen.log - -rm -f $(srcdir)/ctypesgen/ctypesgen/*.pyc - -rm -f $(srcdir)/ctypesgen/ctypesgen/*/*.pyc + PYTHONPATH=$(srcdir)/ctypesgen:${PYTHONPATH} $(PYTHON) $(srcdir)/ctypesgen/ctypesgen.py $(HDF5FLAGS) -lLanlGeoMag --no-macro-warnings -o Lgm_Wrap_gen.py --compile-libdir=$(top_builddir)/libLanlGeoMag/.libs --runtime-libdir=RUNTIME_LIBDIR --includedir=$(LGMSRCDIR)/Lgm --includedir=$(LGMSRCDIR) $(LGMSRCDIR)/Lgm/*.h >ctypesgen.log 2>ctypesgen.log + -rm -f $(srcdir)/ctypesgen/ctypesgencore/*.pyc + -rm -f $(srcdir)/ctypesgen/ctypesgencore/*/*.pyc #only make final Lgm_Wrap on install, so it can rewrite the library directory Lgm_Wrap.py: FORCE Lgm_Wrap_gen.py - $(SED) -e 's|^add_library_search_dirs(\[\(.*\)'\''RUNTIME_LIBDIR'\''\(.*\)\])$$|add_library_search_dirs(\[\1'\''$(libdir)'\''\2\])|' Lgm_Wrap_gen.py > Lgm_Wrap.py + $(SED) -e 's|add_library_search_dirs(\['\''RUNTIME_LIBDIR'\''\])|add_library_search_dirs(\['\''$(libdir)'\''\])|' Lgm_Wrap_gen.py > Lgm_Wrap.py uninstall-hook: -rmdir $(lgmpydir) diff --git a/Python/ctypesgen/README b/Python/ctypesgen/README index 05c23059d..7878a1baa 100644 --- a/Python/ctypesgen/README +++ b/Python/ctypesgen/README @@ -1,54 +1,13 @@ ctypesgen --------- - (c) Ctypesgen developers 2007-2015 - https://github.com/davidjamesca/ctypesgen + (c) Ctypesgen developers 2007-2011 + http://code.google.com/p/ctypesgen/ ctypesgen is a pure-python ctypes wrapper generator. It can also output JSON, which can be used with Mork, which generates bindings for Lua, using the alien module (which binds libffi to Lua). -Documentation -------------- - -See https://github.com/davidjamesca/ctypesgen/wiki for full documentation. - -Basic Usage ------------ - -This project automatically generates ctypes wrappers for header files written -in C. - -For example, if you'd like to generate Neon bindings, you can do so using this -recipe: - - $ python ctypesgen.py -lneon /usr/local/include/neon/ne_*.h -o neon.py - -Some libraries, such as APR, need special flags to compile. You can pass these -flags in on the command line. - -For example: - -$ FLAGS = `apr-1-config --cppflags --includes` -$ python ctypesgen.py $FLAGS -llibapr-1.so $HOME/include/apr-1/apr*.h -o apr.py - -Sometimes, libraries will depend on each other. You can specify these -dependencies using -mmodule, where module is the name of the dependency module. - -Here's an example for apr_util: - -$ python ctypesgen.py $FLAGS -llibaprutil-1.so $HOME/include/apr-1/ap[ru]*.h \ - -mapr -o apr_util.py - - -If you want JSON output (e.g. for generating Lua bindings), use ---output-language=json. When outputting JSON, you will probably want to use ---all-headers --builtin-symbols --no-stddef-types --no-gnu-types ---no-python-types too. - -License -------- - ctypesgen is distributed under the New (2-clause) BSD License: http://www.opensource.org/licenses/bsd-license.php @@ -57,3 +16,11 @@ http://sources.redhat.com/libffi/ Mork, the friendly alien, can be found at: https://github.com/rrthomas/mork + + +Usage +----- + +To get JSON output, use --output-language=json. When outputting JSON, +you will probably want to use --all-headers --builtin-symbols +--no-stddef-types --no-gnu-types --no-python-types too. diff --git a/Python/ctypesgen/demo/demoapp.py b/Python/ctypesgen/demo/demoapp.py old mode 100755 new mode 100644 index 7b801f4db..84baaffc9 --- a/Python/ctypesgen/demo/demoapp.py +++ b/Python/ctypesgen/demo/demoapp.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python # -*- coding: us-ascii -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab """ @@ -22,9 +22,9 @@ def do_demo(): a = 1 b = 2 result = pydemolib.trivial_add(a, b) - print("a", a) - print("b", b) - print("result", result) + print "a", a + print "b", b + print "result", result def main(argv=None): diff --git a/Python/ctypesgen/demo/pydemolib.py b/Python/ctypesgen/demo/pydemolib.py index 37445fb11..ec4b651e0 100644 --- a/Python/ctypesgen/demo/pydemolib.py +++ b/Python/ctypesgen/demo/pydemolib.py @@ -1,14 +1,14 @@ '''Wrapper for demolib.h Generated with: -../run.py -o pydemolib.py -l demolib.so demolib.h +../ctypesgen.py -o pydemolib.py -l demolib.so demolib.h Do not modify this file. ''' __docformat__ = 'restructuredtext' -# Begin preamble for Python v(3, 6) +# Begin preamble import ctypes, os, sys from ctypes import * @@ -25,21 +25,41 @@ del t del _int_types +class c_void(Structure): + # c_void_p is a buggy return type, converting to int, so + # POINTER(None) == c_void_p is actually written as + # POINTER(c_void), so it can be treated as a real pointer. + _fields_ = [('dummy', c_int)] + +def POINTER(obj): + p = ctypes.POINTER(obj) + + # Convert None to a real NULL pointer to work around bugs + # in how ctypes handles None on 64-bit platforms + if not isinstance(p.from_param, classmethod): + def from_param(cls, x): + if x is None: + return cls() + else: + return x + p.from_param = classmethod(from_param) + + return p + class UserString: def __init__(self, seq): - if isinstance(seq, bytes): + if isinstance(seq, basestring): self.data = seq elif isinstance(seq, UserString): self.data = seq.data[:] else: - self.data = str(seq).encode() - def __bytes__(self): return self.data - def __str__(self): return self.data.decode() + self.data = str(seq) + def __str__(self): return str(self.data) def __repr__(self): return repr(self.data) - def __int__(self): return int(self.data.decode()) - def __long__(self): return int(self.data.decode()) - def __float__(self): return float(self.data.decode()) - def __complex__(self): return complex(self.data.decode()) + def __int__(self): return int(self.data) + def __long__(self): return long(self.data) + def __float__(self): return float(self.data) + def __complex__(self): return complex(self.data) def __hash__(self): return hash(self.data) def __cmp__(self, string): @@ -47,37 +67,6 @@ def __cmp__(self, string): return cmp(self.data, string.data) else: return cmp(self.data, string) - def __le__(self, string): - if isinstance(string, UserString): - return self.data <= string.data - else: - return self.data <= string - def __lt__(self, string): - if isinstance(string, UserString): - return self.data < string.data - else: - return self.data < string - def __ge__(self, string): - if isinstance(string, UserString): - return self.data >= string.data - else: - return self.data >= string - def __gt__(self, string): - if isinstance(string, UserString): - return self.data > string.data - else: - return self.data > string - def __eq__(self, string): - if isinstance(string, UserString): - return self.data == string.data - else: - return self.data == string - def __ne__(self, string): - if isinstance(string, UserString): - return self.data != string.data - else: - return self.data != string - def __contains__(self, char): return char in self.data @@ -90,15 +79,15 @@ def __getslice__(self, start, end): def __add__(self, other): if isinstance(other, UserString): return self.__class__(self.data + other.data) - elif isinstance(other, bytes): + elif isinstance(other, basestring): return self.__class__(self.data + other) else: - return self.__class__(self.data + str(other).encode()) + return self.__class__(self.data + str(other)) def __radd__(self, other): - if isinstance(other, bytes): + if isinstance(other, basestring): return self.__class__(other + self.data) else: - return self.__class__(str(other).encode() + self.data) + return self.__class__(str(other) + self.data) def __mul__(self, n): return self.__class__(self.data*n) __rmul__ = __mul__ @@ -109,7 +98,7 @@ def __mod__(self, args): def capitalize(self): return self.__class__(self.data.capitalize()) def center(self, width, *args): return self.__class__(self.data.center(width, *args)) - def count(self, sub, start=0, end=sys.maxsize): + def count(self, sub, start=0, end=sys.maxint): return self.data.count(sub, start, end) def decode(self, encoding=None, errors=None): # XXX improve this? if encoding: @@ -127,13 +116,13 @@ def encode(self, encoding=None, errors=None): # XXX improve this? return self.__class__(self.data.encode(encoding)) else: return self.__class__(self.data.encode()) - def endswith(self, suffix, start=0, end=sys.maxsize): + def endswith(self, suffix, start=0, end=sys.maxint): return self.data.endswith(suffix, start, end) def expandtabs(self, tabsize=8): return self.__class__(self.data.expandtabs(tabsize)) - def find(self, sub, start=0, end=sys.maxsize): + def find(self, sub, start=0, end=sys.maxint): return self.data.find(sub, start, end) - def index(self, sub, start=0, end=sys.maxsize): + def index(self, sub, start=0, end=sys.maxint): return self.data.index(sub, start, end) def isalpha(self): return self.data.isalpha() def isalnum(self): return self.data.isalnum() @@ -153,9 +142,9 @@ def partition(self, sep): return self.data.partition(sep) def replace(self, old, new, maxsplit=-1): return self.__class__(self.data.replace(old, new, maxsplit)) - def rfind(self, sub, start=0, end=sys.maxsize): + def rfind(self, sub, start=0, end=sys.maxint): return self.data.rfind(sub, start, end) - def rindex(self, sub, start=0, end=sys.maxsize): + def rindex(self, sub, start=0, end=sys.maxint): return self.data.rindex(sub, start, end) def rjust(self, width, *args): return self.__class__(self.data.rjust(width, *args)) @@ -167,7 +156,7 @@ def split(self, sep=None, maxsplit=-1): def rsplit(self, sep=None, maxsplit=-1): return self.data.rsplit(sep, maxsplit) def splitlines(self, keepends=0): return self.data.splitlines(keepends) - def startswith(self, prefix, start=0, end=sys.maxsize): + def startswith(self, prefix, start=0, end=sys.maxint): return self.data.startswith(prefix, start, end) def strip(self, chars=None): return self.__class__(self.data.strip(chars)) def swapcase(self): return self.__class__(self.data.swapcase()) @@ -210,10 +199,10 @@ def __setslice__(self, start, end, sub): start = max(start, 0); end = max(end, 0) if isinstance(sub, UserString): self.data = self.data[:start]+sub.data+self.data[end:] - elif isinstance(sub, bytes): + elif isinstance(sub, basestring): self.data = self.data[:start]+sub+self.data[end:] else: - self.data = self.data[:start]+str(sub).encode()+self.data[end:] + self.data = self.data[:start]+str(sub)+self.data[end:] def __delslice__(self, start, end): start = max(start, 0); end = max(end, 0) self.data = self.data[:start] + self.data[end:] @@ -222,10 +211,10 @@ def immutable(self): def __iadd__(self, other): if isinstance(other, UserString): self.data += other.data - elif isinstance(other, bytes): + elif isinstance(other, basestring): self.data += other else: - self.data += str(other).encode() + self.data += str(other) return self def __imul__(self, n): self.data *= n @@ -237,8 +226,8 @@ class String(MutableString, Union): ('data', c_char_p)] def __init__(self, obj=""): - if isinstance(obj, (bytes, UserString)): - self.data = bytes(obj) + if isinstance(obj, (str, unicode, UserString)): + self.data = str(obj) else: self.raw = obj @@ -254,13 +243,9 @@ def from_param(cls, obj): elif isinstance(obj, String): return obj - # Convert from bytes - elif isinstance(obj, bytes): - return cls(obj) - # Convert from str elif isinstance(obj, str): - return cls(obj.encode()) + return cls(obj) # Convert from c_char_p elif isinstance(obj, c_char_p): @@ -274,10 +259,6 @@ def from_param(cls, obj): elif isinstance(obj, int): return cls(cast(obj, POINTER(c_char))) - # Convert from c_char array - elif isinstance(obj, c_char*len(obj)): - return obj - # Convert from object else: return String.from_param(obj._as_parameter_) @@ -294,7 +275,7 @@ def ReturnString(obj, func=None, arguments=None): # Non-primitive return values wrapped with UNCHECKED won't be # typechecked, and will be converted to c_void_p. def UNCHECKED(type): - if (hasattr(type, "_type_") and isinstance(type._type_, bytes) + if (hasattr(type, "_type_") and isinstance(type._type_, str) and type._type_ != "P"): return type else: @@ -303,12 +284,10 @@ def UNCHECKED(type): # ctypes doesn't have direct support for variadic functions, so we have to write # our own wrapper class class _variadic_function(object): - def __init__(self,func,restype,argtypes,errcheck): + def __init__(self,func,restype,argtypes): self.func=func self.func.restype=restype self.argtypes=argtypes - if errcheck: - self.func.errcheck = errcheck def _as_parameter_(self): # So we can pass this variadic function as a function pointer return self.func @@ -363,7 +342,6 @@ def __call__(self,*args): # ---------------------------------------------------------------------------- import os.path, re, sys, glob -import platform import ctypes import ctypes.util @@ -398,7 +376,7 @@ def load(self,path): return ctypes.CDLL(path, ctypes.RTLD_GLOBAL) else: return ctypes.cdll.LoadLibrary(path) - except OSError as e: + except OSError,e: raise ImportError(e) def getpaths(self,libname): @@ -495,26 +473,10 @@ def _create_ld_so_cache(self): directories.append(".") directories.append(os.path.dirname(__file__)) - try: - with open('/etc/ld.so.conf') as f: - directories.extend([dir.strip() for dir in f]) + try: directories.extend([dir.strip() for dir in open('/etc/ld.so.conf')]) except IOError: pass - unix_lib_dirs_list = ['/lib', '/usr/lib', '/lib64', '/usr/lib64'] - if sys.platform.startswith('linux'): - # Try and support multiarch work in Ubuntu - # https://wiki.ubuntu.com/MultiarchSpec - bitage = platform.architecture()[0] - if bitage.startswith('32'): - # Assume Intel/AMD x86 compat - unix_lib_dirs_list += ['/lib/i386-linux-gnu', '/usr/lib/i386-linux-gnu'] - elif bitage.startswith('64'): - # Assume Intel/AMD x86 compat - unix_lib_dirs_list += ['/lib/x86_64-linux-gnu', '/usr/lib/x86_64-linux-gnu'] - else: - # guess... - unix_lib_dirs_list += glob.glob('/lib/*linux-gnu') - directories.extend(unix_lib_dirs_list) + directories.extend(['/lib', '/usr/lib', '/lib64', '/usr/lib64']) cache = {} lib_re = re.compile(r'lib(.*)\.s[ol]') @@ -615,16 +577,7 @@ def getplatformpaths(self, libname): loader = loaderclass.get(sys.platform, PosixLibraryLoader)() def add_library_search_dirs(other_dirs): - """ - Add libraries to search paths. - If library paths are relative, convert them to absolute with respect to this - file's directory - """ - THIS_DIR = os.path.dirname(__file__) - for F in other_dirs: - if not os.path.isabs(F): - F = os.path.abspath(os.path.join(THIS_DIR,F)) - loader.other_dirs.append(F) + loader.other_dirs = other_dirs load_library = loader.load_library @@ -635,6 +588,7 @@ def add_library_search_dirs(other_dirs): add_library_search_dirs([]) # Begin libraries + _libs["demolib.so"] = load_library("demolib.so") # 1 libraries @@ -642,7 +596,7 @@ def add_library_search_dirs(other_dirs): # No modules -# /home/olsonse/src/ctypesgen/demo/demolib.h: 6 +# /home/clach04/dev/python/ctypesgen/demo/demolib.h: 6 if hasattr(_libs['demolib.so'], 'trivial_add'): trivial_add = _libs['demolib.so'].trivial_add trivial_add.argtypes = [c_int, c_int] diff --git a/Python/ctypesgen/setup.py b/Python/ctypesgen/setup.py index 14dfc304b..72c64c6fc 100755 --- a/Python/ctypesgen/setup.py +++ b/Python/ctypesgen/setup.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python # -*- coding: us-ascii -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab """Examples: @@ -8,45 +8,18 @@ """ -import os -from setuptools import setup, find_packages - -THIS_DIR = os.path.dirname( __file__ ) - -import ctypesgen - -ctypesgen.version.write_version_file() - -VERSION_FILE = os.path.relpath(ctypesgen.version.VERSION_FILE, THIS_DIR) -f = open('MANIFEST.in', 'w') -f.write('include {}\n'.format(VERSION_FILE)) -f.write('graft ctypesgen\n') -f.close() - -try: - setup( - name='ctypesgen', - version=ctypesgen.VERSION.partition('-g')[0], - description='Python wrapper generator for ctypes', - long_description= - 'ctypesgen reads parses c header files and creates a wrapper for ' - 'libraries base on what it finds. Preprocessor macros are handled ' - 'in a manner consistent with typical c code. Preprocessor macro ' - 'functions are translated into Python functions that are then made ' - 'available to the user of the newly-generated Python wrapper ' - 'library.\n' - 'ctypesgen can also output JSON, which can be used with Mork, ' - 'which generates bindings for Lua, using the alien module (which ' - 'binds libffi to Lua).', - url='https://github.com/olsonse/ctypesgen', - license='BSD License', - packages=find_packages(), - include_package_data=True, - entry_points={ - 'console_scripts': [ - 'ctypesgen = ctypesgen.main:main', - ], - }, - ) -finally: - os.unlink('MANIFEST.in') +from distutils.core import setup + +import ctypesgencore + +setup(name='ctypesgen', + version=ctypesgencore.VERSION, + description='Python wrapper generator for ctypes', + url='http://code.google.com/p/ctypesgen/', + license='BSD License', + packages=['ctypesgencore', + 'ctypesgencore.parser', + 'ctypesgencore.printer_python', + 'ctypesgencore.printer_json', + 'ctypesgencore.processor'], + scripts=['ctypesgen.py']) diff --git a/Python/ctypesgen/test/ctypesgentest.py b/Python/ctypesgen/test/ctypesgentest.py index ee505a6bc..590a12b02 100644 --- a/Python/ctypesgen/test/ctypesgentest.py +++ b/Python/ctypesgen/test/ctypesgentest.py @@ -1,18 +1,12 @@ import os import sys -import io +import StringIO import optparse import glob -try: - # should succeed for py3 - from importlib import reload as reload_module -except: - reload_module = reload - sys.path.append(".") # Allow tests to be called from parent directory with Python 2.6 sys.path.append("..") -import ctypesgen +import ctypesgencore """ctypesgentest is a simple module for testing ctypesgen on various C constructs. It consists of a single function, test(). test() takes a string that represents a C header file, along with some @@ -26,26 +20,25 @@ def test(header, **more_options): assert isinstance(header, str) - with open("temp.h", "w") as f: - f.write(header) + file("temp.h", "w").write(header) - options = ctypesgen.options.get_default_options() + options = ctypesgencore.options.get_default_options() options.headers = ["temp.h"] for opt in more_options: setattr(options, opt, more_options[opt]) if redirect_stdout: # Redirect output - sys.stdout = io.StringIO() + sys.stdout = StringIO.StringIO() # Step 1: Parse - descriptions = ctypesgen.parser.parse(options.headers, options) + descriptions = ctypesgencore.parser.parse(options.headers, options) # Step 2: Process - ctypesgen.processor.process(descriptions, options) + ctypesgencore.processor.process(descriptions, options) # Step 3: Print - ctypesgen.printer.WrapperPrinter("temp.py", options, descriptions) + ctypesgencore.printer.WrapperPrinter("temp.py", options, descriptions) if redirect_stdout: # Un-redirect output @@ -57,7 +50,7 @@ def test(header, **more_options): # Load the module we have just produced module = __import__("temp") - reload_module(module) # import twice, this hack ensure that "temp" is force loaded (there *must* be a better way to do this) + reload(module) # import twice, this hack ensure that "temp" is force loaded (there *must* be a better way to do this) return module, output diff --git a/Python/ctypesgen/test/testsuite.py b/Python/ctypesgen/test/testsuite.py index 71db8fbc4..fade9046c 100755 --- a/Python/ctypesgen/test/testsuite.py +++ b/Python/ctypesgen/test/testsuite.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python # -*- coding: ascii -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # @@ -7,11 +7,11 @@ Calling: - python test/testsuite.py + python test/testsuite.py or cd test - ./testsuite.py + ./testsuite.py Could use any unitest compatible test runner (nose, etc.) @@ -38,7 +38,7 @@ class StdlibTest(unittest.TestCase): - + def setUp(self): """NOTE this is called once for each test* method (it is not called once per class). @@ -65,12 +65,12 @@ def test_getenv_returns_string(self): Test that we get a valid (non-NULL, non-empty) string back """ module = self.module - + if sys.platform == "win32": # Check a variable that is already set env_var_name = 'USERNAME' # this is always set (as is windir, ProgramFiles, USERPROFILE, etc.) expect_result = os.environ[env_var_name] - self.assertTrue(expect_result, 'this should not be None or empty') + self.assert_(expect_result, 'this should not be None or empty') # reason for using an existing OS variable is that unless the # MSVCRT dll imported is the exact same one that Python was # built with you can't share structures, see @@ -80,9 +80,9 @@ def test_getenv_returns_string(self): env_var_name = 'HELLO' os.environ[env_var_name] = 'WORLD' # This doesn't work under win32 expect_result = 'WORLD' - - result = str(module.getenv(env_var_name)) - self.assertEqual(expect_result, result) + + result = module.getenv(env_var_name) + self.failUnlessEqual(expect_result, result) def test_getenv_returns_null(self): """Related to issue 8. Test getenv of unset variable. @@ -96,7 +96,7 @@ def test_getenv_returns_null(self): except KeyError: pass result = module.getenv(env_var_name) - self.assertEqual(expect_result, result) + self.failUnlessEqual(expect_result, result) class StdBoolTest(unittest.TestCase): @@ -121,18 +121,18 @@ def setUp(self): def tearDown(self): del self.module ctypesgentest.cleanup() - + def test_stdbool_type(self): """Test is bool is correctly parsed""" module = self.module struct_foo = module.struct_foo - self.assertEqual(struct_foo._fields_, [("is_bar", ctypes.c_bool), ("a", ctypes.c_int)]) + self.failUnlessEqual(struct_foo._fields_, [("is_bar", ctypes.c_bool), ("a", ctypes.c_int)]) class SimpleMacrosTest(unittest.TestCase): """Based on simple_macros.py """ - + def setUp(self): """NOTE this is called once for each test* method (it is not called once per class). @@ -147,10 +147,6 @@ def setUp(self): #define minus_macro(x,y) x-y #define divide_macro(x,y) x/y #define mod_macro(x,y) x%y -#define subcall_macro_simple(x) (A) -#define subcall_macro_simple_plus(x) (A) + (x) -#define subcall_macro_minus(x,y) minus_macro(x,y) -#define subcall_macro_minus_plus(x,y,z) (minus_macro(x,y)) + (z) ''' libraries = None self.module, output = ctypesgentest.test(header_str) @@ -163,154 +159,92 @@ def test_macro_constant_int(self): """Tests from simple_macros.py """ module = self.module - - self.assertEqual(module.A, 1) + + self.failUnlessEqual(module.A, 1) def test_macro_addition(self): """Tests from simple_macros.py """ module = self.module - - self.assertEqual(module.B(2, 2), 4) + + self.failUnlessEqual(module.B(2, 2), 4) def test_macro_ternary_true(self): """Tests from simple_macros.py """ module = self.module - - self.assertEqual(module.C(True, 1, 2), 1) + + self.failUnlessEqual(module.C(True, 1, 2), 1) def test_macro_ternary_false(self): """Tests from simple_macros.py """ module = self.module - - self.assertEqual(module.C(False, 1, 2), 2) + + self.failUnlessEqual(module.C(False, 1, 2), 2) def test_macro_ternary_true_complex(self): """Test ?: with true, using values that can not be confused between True and 1 """ module = self.module - - self.assertEqual(module.C(True, 99, 100), 99) + + self.failUnlessEqual(module.C(True, 99, 100), 99) def test_macro_ternary_false_complex(self): """Test ?: with false, using values that can not be confused between True and 1 """ module = self.module - - self.assertEqual(module.C(False, 99, 100), 100) + + self.failUnlessEqual(module.C(False, 99, 100), 100) def test_macro_string_compose(self): """Tests from simple_macros.py """ module = self.module - - self.assertEqual(module.funny("bunny"), "funnybunny") - + + self.failUnlessEqual(module.funny("bunny"), "funnybunny") + def test_macro_math_multipler(self): module = self.module - + x, y = 2, 5 - self.assertEqual(module.multipler_macro(x, y), x * y) + self.failUnlessEqual(module.multipler_macro(x, y), x * y) def test_macro_math_minus(self): module = self.module - + x, y = 2, 5 - self.assertEqual(module.minus_macro(x, y), x - y) + self.failUnlessEqual(module.minus_macro(x, y), x - y) def test_macro_math_divide(self): module = self.module - + x, y = 2, 5 - self.assertEqual(module.divide_macro(x, y), x / y) + self.failUnlessEqual(module.divide_macro(x, y), x / y) def test_macro_math_mod(self): module = self.module - - x, y = 2, 5 - self.assertEqual(module.mod_macro(x, y), x % y) - - def test_macro_subcall_simple(self): - """Test use of a constant valued macro within a macro""" - module = self.module - - self.assertEqual(module.subcall_macro_simple(2), 1) - - def test_macro_subcall_simple_plus(self): - """Test math with constant valued macro within a macro""" - module = self.module - - self.assertEqual(module.subcall_macro_simple_plus(2), 1 + 2) - - def test_macro_subcall_minus(self): - """Test use of macro function within a macro""" - module = self.module - + x, y = 2, 5 - self.assertEqual(module.subcall_macro_minus(x, y), x - y) - - def test_macro_subcall_minus_plus(self): - """Test math with a macro function within a macro""" - module = self.module - - x, y, z = 2, 5, 1 - self.assertEqual(module.subcall_macro_minus_plus(x, y, z), (x - y) + z) + self.failUnlessEqual(module.mod_macro(x, y), x % y) class StructuresTest(unittest.TestCase): """Based on structures.py """ - + def setUp(self): """NOTE this is called once for each test* method (it is not called once per class). FIXME This is slightly inefficient as it is called *way* more times than it needs to be. """ header_str = ''' - struct foo { int a; - char b; + int b; int c; - int d : 15; - int : 17; }; - -struct __attribute__((packed)) packed_foo -{ - int a; - char b; - int c; - int d : 15; - int : 17; -}; - -typedef struct -{ - int a; - char b; - int c; - int d : 15; - int : 17; -} foo_t; - -typedef struct __attribute__((packed)) -{ - int a; - char b; - int c; - int d : 15; - int : 17; -} packed_foo_t; - -typedef int Int; - -typedef struct { - int Int; -} id_struct_t; ''' libraries = None self.module, output = ctypesgentest.test(header_str) @@ -319,57 +253,24 @@ def tearDown(self): del self.module ctypesgentest.cleanup() - def test_fields(self): - """Test whether fields are built correctly. - """ - struct_foo = self.module.struct_foo - self.assertEqual(struct_foo._fields_, - [("a", ctypes.c_int), ("b", ctypes.c_char), ("c", ctypes.c_int), - ("d", ctypes.c_int, 15), ("unnamed_1", ctypes.c_int, 17) - ] - ) - - def test_pack(self): - """Test whether gcc __attribute__((packed)) is interpreted correctly. + def test_structures(self): + """Tests from structures.py """ - unpacked_size = ctypes.sizeof(ctypes.c_int)*4 - packed_size = ctypes.sizeof(ctypes.c_int)*3 + ctypes.sizeof(ctypes.c_char) - - struct_foo = self.module.struct_foo - struct_packed_foo = self.module.struct_packed_foo - foo_t = self.module.foo_t - packed_foo_t = self.module.packed_foo_t - self.assertEqual(getattr(struct_foo, '_pack_', 0), 0) - self.assertEqual(getattr(struct_packed_foo, '_pack_', 0), 1) - self.assertEqual(getattr(foo_t, '_pack_', 0), 0) - self.assertEqual(getattr(packed_foo_t, '_pack_', -1), 1) - self.assertEqual(ctypes.sizeof(struct_foo), unpacked_size) - self.assertEqual(ctypes.sizeof(foo_t), unpacked_size) - self.assertEqual(ctypes.sizeof(struct_packed_foo), packed_size) - self.assertEqual(ctypes.sizeof(packed_foo_t), packed_size) - - def test_typedef_vs_field_id(self): - """Test whether local field identifier names can override external - typedef names. - """ - Int = self.module.Int - id_struct_t = self.module.id_struct_t - self.assertEqual(Int, ctypes.c_int) - self.assertEqual(id_struct_t._fields_, [("Int", ctypes.c_int)]) + module = self.module + + struct_foo = module.struct_foo + self.failUnlessEqual(struct_foo._fields_, [("a", ctypes.c_int), ("b", ctypes.c_int), ("c", ctypes.c_int)]) class MathTest(unittest.TestCase): """Based on math_functions.py""" - + def setUp(self): """NOTE this is called once for each test* method (it is not called once per class). FIXME This is slightly inefficient as it is called *way* more times than it needs to be. """ - header_str = ''' -#include -#define sin_plus_y(x,y) (sin(x) + (y)) -''' + header_str = '#include \n' if sys.platform == "win32": # pick something from %windir%\system32\msvc*dll that include stdlib libraries = ["msvcrt.dll"] @@ -387,43 +288,37 @@ def tearDown(self): def test_sin(self): """Based on math_functions.py""" module = self.module - - self.assertEqual(module.sin(2), math.sin(2)) + + self.failUnlessEqual(module.sin(2), math.sin(2)) def test_sqrt(self): """Based on math_functions.py""" module = self.module - - self.assertEqual(module.sqrt(4), 2) + + self.failUnlessEqual(module.sqrt(4), 2) def local_test(): module.sin("foobar") - - self.assertRaises(ctypes.ArgumentError, local_test) + + self.failUnlessRaises(ctypes.ArgumentError, local_test) def test_bad_args_string_not_number(self): """Based on math_functions.py""" module = self.module - + def local_test(): module.sin("foobar") - - self.assertRaises(ctypes.ArgumentError, local_test) - - def test_subcall_sin(self): - """Test math with sin(x) in a macro""" - module = self.module - - self.assertEqual(module.sin_plus_y(2,1), math.sin(2) + 1) + + self.failUnlessRaises(ctypes.ArgumentError, local_test) def main(argv=None): if argv is None: argv = sys.argv - - ctypesgentest.ctypesgen.messages.log.setLevel(logging.CRITICAL) # do not log anything + + ctypesgentest.ctypesgencore.messages.log.setLevel(logging.CRITICAL) # do not log anything unittest.main() - + return 0 diff --git a/Python/lgmpy/Lstar.py b/Python/lgmpy/Lstar.py index 2d3a296ce..763e61130 100644 --- a/Python/lgmpy/Lstar.py +++ b/Python/lgmpy/Lstar.py @@ -28,7 +28,7 @@ import Lgm_Wrap from Lgm_Wrap import Lgm_Set_Coord_Transforms, SM_TO_GSM, Lgm_Convert_Coords, \ Lgm_SetLstarTolerances, RadPerDeg, GSM_TO_WGS84, WGS84_TO_EDMAG,\ - Lgm_McIlwain_L, Lgm_EDMAG_to_R_MLAT_MLON_MLT, Lgm_FreeMagEphemInfo_Children, \ + LFromIBmM_Hilton, LFromIBmM_McIlwain, Lgm_EDMAG_to_R_MLAT_MLON_MLT, Lgm_FreeMagEphemInfo_Children, \ Lgm_ComputeLstarVersusPA, Lgm_B_TS04, Lgm_B_T96, Lgm_QinDentonOne, Lgm_set_QinDenton, Lgm_get_QinDenton_at_JD from Lgm_Wrap import Lstar as Lgm_Lstar import Lgm_Vector @@ -412,24 +412,18 @@ def get_Lstar(pos, date, alpha = 90., MagEphemInfo.Bm[i] = MagEphemInfo.LstarInfo.contents.mInfo.contents.Bm # Compute L* if Lsimple < LstarThresh: - Ls_vec = Lgm_Vector.Lgm_Vector(Pgsm.x, Pgsm.y, Pgsm.z) + Ls_vec = Lgm_Vector.Lgm_Vector(*minB) LS_Flag = Lgm_Lstar( pointer(Ls_vec), MagEphemInfo.LstarInfo) lstarinf = MagEphemInfo.LstarInfo.contents #shortcut - #Returned from McIlwain_L but not used here - Ijunk = c_double() - Bmjunk = c_double() - Mjunk = c_double() - MagEphemInfo.LHilton.contents.value = Lgm_McIlwain_L( - MagEphemInfo.Date, MagEphemInfo.UTC, pointer(MagEphemInfo.P), - pa, 1, pointer(Ijunk), pointer(Bmjunk), pointer(Mjunk), - lstarinf.mInfo) + MagEphemInfo.LHilton.contents.value = LFromIBmM_Hilton(c_double(lstarinf.I[0]), + c_double(MagEphemInfo.Bm[i]), + c_double(lstarinf.mInfo.contents.c.contents.M_cd)) ans[pa]['LHilton'] = MagEphemInfo.LHilton.contents.value - MagEphemInfo.LMcIlwain.contents.value = Lgm_McIlwain_L( - MagEphemInfo.Date, MagEphemInfo.UTC, pointer(MagEphemInfo.P), - pa, 0, pointer(Ijunk), pointer(Bmjunk), pointer(Mjunk), - lstarinf.mInfo) + MagEphemInfo.LMcIlwain.contents.value = LFromIBmM_McIlwain(c_double(lstarinf.I[0]), + c_double(MagEphemInfo.Bm[i]), + c_double(lstarinf.mInfo.contents.c.contents.M_cd)) ans[pa]['LMcIlwain'] = MagEphemInfo.LMcIlwain.contents.value if LS_Flag == -2: # mirror below southern hemisphere mirror alt ans[pa]['Lstar'] = datamodel.dmarray([numpy.nan], attrs={'info':'S_LOSS'}) @@ -852,19 +846,13 @@ def get_Lstar_General(pos, date, alpha = 90., LS_Flag = Lgm_Lstar( pointer(Ls_vec), MagEphemInfo.LstarInfo) lstarinf = MagEphemInfo.LstarInfo.contents #shortcut - #Returned from McIlwain_L but not used here - Ijunk = c_double() - Bmjunk = c_double() - Mjunk = c_double() - MagEphemInfo.LHilton.contents.value = Lgm_McIlwain_L( - MagEphemInfo.Date, MagEphemInfo.UTC, pointer(MagEphemInfo.P), - pa, 1, pointer(Ijunk), pointer(Bmjunk), pointer(Mjunk), - lstarinf.mInfo) + MagEphemInfo.LHilton.contents.value = LFromIBmM_Hilton(c_double(lstarinf.I[0]), + c_double(MagEphemInfo.Bm[i]), + c_double(lstarinf.mInfo.contents.c.contents.M_cd)) ans[pa]['LHilton'] = MagEphemInfo.LHilton.contents.value - MagEphemInfo.LMcIlwain.contents.value = Lgm_McIlwain_L( - MagEphemInfo.Date, MagEphemInfo.UTC, pointer(MagEphemInfo.P), - pa, 0, pointer(Ijunk), pointer(Bmjunk), pointer(Mjunk), - lstarinf.mInfo) + MagEphemInfo.LMcIlwain.contents.value = LFromIBmM_McIlwain(c_double(lstarinf.I[0]), + c_double(MagEphemInfo.Bm[i]), + c_double(lstarinf.mInfo.contents.c.contents.M_cd)) ans[pa]['LMcIlwain'] = MagEphemInfo.LMcIlwain.contents.value if LS_Flag == -2: # mirror below southern hemisphere mirror alt ans[pa]['Lstar'] = datamodel.dmarray([numpy.nan], attrs={'info':'S_LOSS'}) diff --git a/Python/lgmpy/__init__.py b/Python/lgmpy/__init__.py index 1ff899768..8880da264 100644 --- a/Python/lgmpy/__init__.py +++ b/Python/lgmpy/__init__.py @@ -10,7 +10,7 @@ @version: V1: 06-Dec-2010 (BAL) """ # put modules here that you want to be accessible through 'from spacepy import *' -__all__ = ['Lstar', 'Closed_Field', 'Lgm_T89', 'Lgm_T89c', 'Lgm_OP77'] +__all__ = ['Lstar', 'Closed_Field', 'Lgm_T89', 'Lgm_OP77'] # Expose definitions from modules in this package. from lgmpy.Closed_Field import Closed_Field diff --git a/Python/lgmpy/test_Bfield_dict.py b/Python/lgmpy/test_Bfield_dict.py index 9c32e0939..ca01dedb7 100755 --- a/Python/lgmpy/test_Bfield_dict.py +++ b/Python/lgmpy/test_Bfield_dict.py @@ -18,13 +18,13 @@ def tearDown(self): def test_length(self): """the _Bfield_dict dist should have known length""" - self.assertEqual(len(_Bfield_dict.Bfield_dict), 8) + self.assertEqual(len(_Bfield_dict.Bfield_dict), 7) def test_keys(self): """the _Bfield_dict dist should have known keys""" - keys = ['Lgm_B_OP77', 'Lgm_B_edip', 'Lgm_B_T89', 'Lgm_B_T89c', 'Lgm_B_cdip', 'Lgm_B_T96', 'Lgm_B_Dungey', 'Lgm_B_T01S'] - self.assertEqual( - sorted(keys), sorted(_Bfield_dict.Bfield_dict.keys())) + keys = ['Lgm_B_OP77', 'Lgm_B_edip', 'Lgm_B_T89', 'Lgm_B_T89c', 'Lgm_B_cdip', 'Lgm_B_T96', 'Lgm_B_Dungey'] + for val in keys: + self.assertTrue(val in _Bfield_dict.Bfield_dict) if __name__ == '__main__': diff --git a/Python/lgmpy/test_Closed_Field.py b/Python/lgmpy/test_Closed_Field.py index b1c6739d7..013bf6b55 100755 --- a/Python/lgmpy/test_Closed_Field.py +++ b/Python/lgmpy/test_Closed_Field.py @@ -48,18 +48,15 @@ def test_Closed_Field_Output(self): def test_extended_out(self): """Closed_Field extended_out flag should have known behaviour (regression)""" - ans, north_fp, south_fp, minB, L \ - = Closed_Field([1,2,2], self.date, extended_out=True) - self.assertEqual(ans, 'LGM_CLOSED') - numpy.testing.assert_allclose(north_fp, - [-0.0620421299, 0.39455411901, 0.9306480813], rtol=1e-5) - numpy.testing.assert_allclose(south_fp, - [0.7666220541, 0.3352533669, -0.571429965], rtol=1e-5) - numpy.testing.assert_allclose(minB, - [2.279625676, 2.809834544, 1.1244815844], rtol=1e-5) - #This value isn't tested in the C - #So this is essentially a regression test on _simpleL - self.assertAlmostEqual(L, 3.7371417478198037, places=5) + data = Closed_Field([1,2,2], self.date, extended_out = True) + self.assertEqual(data[0], 'LGM_CLOSED') + numpy.testing.assert_allclose(data[1], + [-0.062054, 0.394555, 0.930685], rtol=1e-4) + numpy.testing.assert_allclose(data[2], + [ 0.76665, 0.33534, -0.57132], rtol=1e-4) + numpy.testing.assert_allclose(data[3], + [ 2.27943481, 2.80962393, 1.12454726], rtol=1e-4) + self.assertAlmostEqual(data[4], 3.737398946245622, places=5) if __name__ == '__main__': diff --git a/Python/lgmpy/test_Lgm_CTrans.py b/Python/lgmpy/test_Lgm_CTrans.py index 81fe0d207..55f8e4abc 100755 --- a/Python/lgmpy/test_Lgm_CTrans.py +++ b/Python/lgmpy/test_Lgm_CTrans.py @@ -155,11 +155,11 @@ def test_getDipoleTilt(self): dt = Lgm_CTrans.getDipoleTilt(datetime.datetime(2000, 1, 1)) self.assertAlmostEqual(dt, -0.45114989442541137) dt = Lgm_CTrans.getDipoleTilt(datetime.datetime(2010, 1, 1)) - self.assertAlmostEqual(dt, -0.4463861347030587) + self.assertAlmostEqual(dt, -0.44636634840305872) dt = Lgm_CTrans.getDipoleTilt(datetime.datetime(2010, 6, 1)) - self.assertAlmostEqual(dt, 0.3243285731455956) + self.assertAlmostEqual(dt, 0.32433439111559559) dt = Lgm_CTrans.getDipoleTilt([datetime.datetime(2010, 6, 1)]*2) - numpy.testing.assert_allclose(dt, [0.3243285731455956, 0.3243285731455956]) + numpy.testing.assert_allclose(dt, [0.32433439111559559, 0.32433439111559559]) if __name__ == '__main__': diff --git a/Python/lgmpy/test_Lgm_OP77.py b/Python/lgmpy/test_Lgm_OP77.py index 02ef3f8e5..22addce46 100755 --- a/Python/lgmpy/test_Lgm_OP77.py +++ b/Python/lgmpy/test_Lgm_OP77.py @@ -63,14 +63,13 @@ def tearDown(self): def test_OP77_1(self): """First simple in/out tests of OP77 (regression)""" - ans = np.array([-18.3504757805, -1.8574883465, 85.6099901369]) + ans = np.array([-18.34951014348532, -1.857515, 85.6100488]) B = Lgm_OP77.Lgm_OP77(self.pos, self.dt) - np.testing.assert_allclose(ans, np.array(B['B'].tolist()), - rtol=1e-8, atol=1e-5) + np.testing.assert_allclose(ans, np.array(B['B'].tolist()), rtol=1e-3, atol=0) def test_list_in(self): """Make sure that list inputs work correctly (regression)""" - ans = [-18.3504757805, -1.8574883465, 85.6099901369] + ans = [-18.34951014348532, -1.8575154402941223, 85.6100478454] a = Lgm_OP77.Lgm_OP77([self.pos]*2, [self.dt]*2) B = a.calc_B() B = [val.tolist() for val in B] diff --git a/Python/lgmpy/test_Lgm_T89.py b/Python/lgmpy/test_Lgm_T89.py index 2a105e5b1..e449ba7f7 100755 --- a/Python/lgmpy/test_Lgm_T89.py +++ b/Python/lgmpy/test_Lgm_T89.py @@ -64,11 +64,11 @@ def tearDown(self): super(Lgm_T89Tests, self).tearDown() def test_T89_1(self): - """First simple in/out tests of T89 (compared to C)""" - ans = [[-18.927076539382270, -1.857488346594122, 80.052089573497625], - [-20.784132182565948, -1.857488346594122, 74.280950924408401], - [-22.513829891596075, -1.857488346594122, 70.183320782457827], - [-26.367918458616543, -1.857488346594122, 64.303840068519463], ] + """First simple in/out tests of T89 (regression)""" + ans = [[-18.92608102838227, -1.8575154402941223, 80.05211611259763], + [-20.783024662565946, -1.8575154402941223, 74.2809609414084 ], + [-22.512615841596073, -1.8575154402941223, 70.18331903086782], + [-26.36648155861654, -1.8575154402941223, 64.30381088411946 ], ] for i, kp in enumerate(range(4)): B = Lgm_T89.Lgm_T89(self.pos, self.dt, kp) self.assertAlmostEqual(ans[i][0], B['B'].x, 5) @@ -85,10 +85,10 @@ def test_kp_checking(self): def test_list_in(self): """Make sure that list inputs work correctly (regression)""" - ans = [[-18.927076539382270, -1.857488346594122, 80.052089573497625], - [-20.784132182565948, -1.857488346594122, 74.280950924408401], - [-22.513829891596075, -1.857488346594122, 70.183320782457827], - [-26.367918458616543, -1.857488346594122, 64.303840068519463]] + ans = [[-18.92608102838227, -1.8575154402941223, 80.05211611259763], + [-20.783024662565946, -1.8575154402941223, 74.2809609414084 ], + [-22.512615841596073, -1.8575154402941223, 70.18331903086782], + [-26.36648155861654, -1.8575154402941223, 64.30381088411946 ], ] for i, kp in enumerate(range(4)): a = Lgm_T89.Lgm_T89([self.pos]*2, [self.dt]*2, [kp]*2) B = a.calc_B() @@ -127,10 +127,13 @@ def test_internal_model_values(self): # values form C test run # Date = 20090101; UTC = 0.0; mInfo->Kp = 2; # u.x = 3.0; u.y = 4.0; u.z = 3.0 + # IGRF: -124.3951334579, -73.9980630146, 78.2480922689 + # CDIP: -123.6039064198, -75.2663431204, 77.7392286024 + # EDIP: -123.5566489251, -72.5155639973, 79.1393833267 ans = {} - ans['IGRF'] = [-123.994265, -73.755273, 77.986302] - ans['CDIP'] = [-123.603699, -75.262705, 77.740849] - ans['EDIP'] = [-122.127613, -75.432215, 79.463218] + ans['IGRF'] = [-123.99486 , -73.758075, 77.98547 ] + ans['CDIP'] = [-123.6039064198, -75.2663431204, 77.7392286024] + ans['EDIP'] = [-123.5566489251, -72.5155639973, 79.1393833267] pos = [3.0, 4.0, 3.0] dt = datetime.datetime(2009, 1, 1, 0) kp = 2 diff --git a/Python/lgmpy/test_Lstar.py b/Python/lgmpy/test_Lstar.py index 4c72570c6..320ef752a 100755 --- a/Python/lgmpy/test_Lstar.py +++ b/Python/lgmpy/test_Lstar.py @@ -36,34 +36,34 @@ def test_Lstar_input(self): def testLgm_B_T89_1(self): """This is a regression functional test for LstarVersusPA (regression)""" ans = Lstar.get_Lstar([-4.2, 1, 1], self.date, alpha = 90, Kp = 4, coord_system='SM', Bfield = 'Lgm_B_T89', LstarQuality = 1) - self.assertAlmostEqual(5.030729110000001, ans[90]['LHilton'], places=4) - self.assertAlmostEqual(5.0308511193, ans[90]['LMcIlwain'], places=4) - self.assertAlmostEqual(4.4572962598000005, ans[90]['Lstar'][0], places=4) + self.assertAlmostEqual(5.02934060, ans[90]['LHilton'], places=4) + self.assertAlmostEqual(5.029461969276, ans[90]['LMcIlwain'], places=4) + self.assertAlmostEqual(4.4572240898083, ans[90]['Lstar'][0], places=4) self.assertAlmostEqual(5.81634438101, ans[90]['Lsimple'][0], places=4) def testLgm_B_T89_2(self): """This is a regression functional test for LstarVersusPA (regression)""" ans = Lstar.get_Lstar([-4.2, 1, 1], self.date, alpha = 90, Kp = 5, coord_system='SM', Bfield = 'Lgm_B_T89', LstarQuality = 1) - self.assertAlmostEqual(5.181867081, ans[90]['LHilton'], places=4) - self.assertAlmostEqual(5.182039616000001, ans[90]['LMcIlwain'], places=4) - self.assertAlmostEqual(4.3583051834, ans[90]['Lstar'][0], places=4) + self.assertAlmostEqual(5.179958506, ans[90]['LHilton'], places=4) + self.assertAlmostEqual(5.180130107, ans[90]['LMcIlwain'], places=4) + self.assertAlmostEqual(4.35824001343, ans[90]['Lstar'][0], places=4) self.assertAlmostEqual(5.46286608758, ans[90]['Lsimple'][0], places=4) def testLgm_B_OP77_1(self): """This is a regression functional test for LstarVersusPA (regression)""" ans = Lstar.get_Lstar([-4.2, 1, 1], self.date, alpha = 90, Kp = 4, coord_system='SM', Bfield = 'Lgm_B_OP77', LstarQuality = 1) - self.assertAlmostEqual(4.8625353534999975, ans[90]['LHilton'], places=4) - self.assertAlmostEqual(4.86261644, ans[90]['LMcIlwain'], places=4) - self.assertAlmostEqual(4.571419493099999, ans[90]['Lstar'][0], places=4) + self.assertAlmostEqual(4.8619543166, ans[90]['LHilton'], places=4) + self.assertAlmostEqual(4.86203516, ans[90]['LMcIlwain'], places=4) + self.assertAlmostEqual(4.571340083084, ans[90]['Lstar'][0], places=4) self.assertAlmostEqual(6.29150825380, ans[90]['Lsimple'][0], places=4) def testLgm_B_OP77_2(self): """This is a regression functional test for LstarVersusPA (regression)""" # should be no change with Kp ans = Lstar.get_Lstar([-4.2, 1, 1], self.date, alpha = 90, Kp = 5, coord_system='SM', Bfield = 'Lgm_B_OP77', LstarQuality = 1) - self.assertAlmostEqual(4.862535358299999, ans[90]['LHilton'], places=4) - self.assertAlmostEqual(4.862616435, ans[90]['LMcIlwain'], places=4) - self.assertAlmostEqual(4.571419493099999, ans[90]['Lstar'][0], places=4) + self.assertAlmostEqual(4.86195431, ans[90]['LHilton'], places=4) + self.assertAlmostEqual(4.862035166, ans[90]['LMcIlwain'], places=4) + self.assertAlmostEqual(4.5713400838, ans[90]['Lstar'][0], places=4) self.assertAlmostEqual(6.29150825, ans[90]['Lsimple'][0], places=4) def testCentredDipole90(self): diff --git a/Python/lgmpy/test_magcoords.py b/Python/lgmpy/test_magcoords.py index b0840a315..2a6a52746 100755 --- a/Python/lgmpy/test_magcoords.py +++ b/Python/lgmpy/test_magcoords.py @@ -28,61 +28,42 @@ def tearDown(self): def test_end2end(self): """quick functional tests (regression)""" - ans = [-3.607999564981572, 1.3877763423443373e-17, -1.726945030766233] + ans = [-3.608026916281572, 4.163336342344337e-17, -1.7268878861662331] numpy.testing.assert_allclose(ans, magcoords.coordTrans([-4,0,0], datetime.datetime(2009,1,1), 'SM','GSM'), atol=1e-8) - ans = [-4., 0., 0.] + ans = [-3.9999999999999991, 1.87350135e-16, 0.00000000e+00] numpy.testing.assert_allclose(ans, - magcoords.coordTrans([-3.607999564981572, 1.3877763423443373e-17, - -1.726945030766233], datetime.datetime(2009,1,1),'GSM','SM'), atol=1e-8) - #Use SphToCart/CartToSph to convert between the C values (always - #cartesian even in WGS84) and the Python ones (WGS84 is spherical) - ans = [-0.8908435824709999, 0.09890080939498999, -0.443414412792] + magcoords.coordTrans([-3.608026916281573, 2.5673907444456745e-16, + -1.7268878861662329], datetime.datetime(2009,1,1),'GSM','SM'), atol=1e-8) + ans = [-0.8908435824705201, 0.09891125760552615, -0.4434120822553017] numpy.testing.assert_allclose(ans, magcoords.coordTrans([-4, 0, 1], datetime.datetime(2009,1,1), 'WGS84', 'GSM'), rtol=1e-6) - ans = [36.76783195260621, -2.3294531575340423, 4.1231056256205525] + ans = [36.7677624344546, -2.329852593118382, 4.12310562561766] numpy.testing.assert_allclose(ans, magcoords.coordTrans([-4, 0, 1], datetime.datetime(2009,1,1), 'GSM', 'WGS84'), rtol=1e-6) - def test_end2end_jpl_eph(self): - """quick functional tests with JPL DE421""" - #Straight from the C - cases = ["2015-03-08T19:18:31.786778 479114378970778386 GEI2000 GSE -72417.672749 -51921.225510 -29798.643397 -58063.063795 -73566.510184 -6688.896414", - "2015-03-11T11:58:40.170326 479347187354325578 GSE2000 SM -20164.747998 -52414.140552 -20241.497772 -20870.283837 -46078.983969 -31697.569507", - "2015-03-12T04:25:43.605928 479406410789928239 SM GSM 75645.819112 -40422.353445 -35182.256254 81628.221639 -40422.353445 -17231.208208"] - for c in cases: - dt, tt, fromsys, tosys, xin, yin, zin, xout, yout, zout = c.split() - dt = datetime.datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%f') - inputs = [float(xin), float(yin), float(zin)] - expected = [float(xout), float(yout), float(zout)] - actual = magcoords.coordTrans( - inputs, dt, fromsys, tosys, de_eph=True) - numpy.testing.assert_allclose(expected, actual, atol=1e-8) - def test_Lvalue(self): """Lvalue should have known output""" - #Default Kp is 2 in both the C and the Python - ans = {'I': 10.9312487946278, 'L': 7.96706218379283} + ans = {'I': 10.9298583451352, 'L': 7.966548339} vals = magcoords.Lvalue([-4, 0, 1], datetime.datetime(2009,1,1)) for key in vals: self.assertAlmostEqual(vals[key], ans[key], places=4) - ans = {'I': 0.69161497288978, 'L': 4.51513147096729} + ans = {'I': 0.6915739190021, 'L': 4.51510833989} vals = magcoords.Lvalue([-4, 0, 1], datetime.datetime(2009,1,1), coord_system='SM') for key in vals: self.assertAlmostEqual(vals[key], ans[key], places=4) def test_Lvalue_extended_out(self): """Lvalue has an extended out (regression)""" - ans = { - 'Blocal': 628.07992515195, - 'Bmin': 21.678823206256, - 'Bmirr': 628.07992515195, - 'I': 10.9312487946278, - 'L': 7.96706218379283, - 'M': 29966.8851195941, + ans = {'Blocal': 628.0753565024, + 'Bmin': 21.686322939, + 'Bmirr': 628.0753565024, + 'I': 10.929858345135273, + 'L': 7.9665483393055, + 'M': 29966.895576135077, 'MLon': 180.0, 'MLT': 0.0, } @@ -113,7 +94,7 @@ def test_input(self): def test_Pin_pos_in(self): """I don't understand why this is here but here is a regression test""" in_pos = Lgm_Vector.Lgm_Vector(-4,0,0) - ans = [-3.607999564981572, 1.3877763423443373e-17, -1.726945030766233] + ans = [-3.608026916281572, 4.163336342344337e-17, -1.7268878861662331] numpy.testing.assert_allclose(ans, magcoords.coordTrans(in_pos, datetime.datetime(2009,1,1),'SM','GSM'), atol=1e-8) @@ -130,13 +111,6 @@ def test_GEO_GSE(self): numpy.testing.assert_allclose([1,2,3], magcoords.coordTrans(expected, datetime.datetime(2012, 3, 4), 'GSE', 'GEO')) - def test_Lvalues_lstar(self): - """Test Hilton/McIlwain for the values used in L* tests""" - #testLgm_B_T89_1 - L = magcoords.Lvalue([-4.2, 1, 1], datetime.datetime(2010, 10, 12), - alpha=90, Kp=4, method='McIlwain', - coord_system='SM', Bfield='Lgm_B_T89')['L'] - self.assertAlmostEqual(5.0293407729574, L, places=7) if __name__ == '__main__': diff --git a/Tools/LastClosedDriftShell.c b/Tools/LastClosedDriftShell.c index 4fee3fd8c..f57788f9e 100644 --- a/Tools/LastClosedDriftShell.c +++ b/Tools/LastClosedDriftShell.c @@ -11,7 +11,6 @@ #include #include #include -#include #define MAIN #define TRACE_TOL 1e-7 @@ -21,7 +20,7 @@ void StringSplit( char *Str, char *StrArray[], int len, int *n ); const char *ProgramName = "LastClosedDriftShell"; -const char *argp_program_version = "LastClosedDriftShell_0.2"; +const char *argp_program_version = "LastClosedDriftShell_0.1"; const char *argp_program_bug_address = ""; static char doc[] = "\nComputes last closed drift shell for given times, Ks and magnetic field model." " \n\n OutFile is a path to the output file(s) that may contain" @@ -30,7 +29,7 @@ static char doc[] = "\nComputes last closed drift shell for given times, Ks and " repectively to 4-digit year, 2-digit month (Jan is 01), and 2-digit day of" " month.\n" " Here is an example using time variables,\n\n \t./LastClosedDriftShell -S 20020901 -E 20020930\n" - " \t\t/home/jsmith/MagEphemData/%YYYY/%YYYY%MM%DD_LCDS_%EE.txt\n\n Directories" + " \t\t/home/jsmith/MagEphemData/%YYYY/%YYYY%MM%DD_LCDS_%EE.txt.\n\n Directories" " in the output file will be created if they don't already exist.\n\n"; @@ -60,7 +59,6 @@ static struct argp_option Options[] = { {"LT", 'L', "LT", 0, "Local time for LCDS search plane. Default is 0 (midnight)." }, {"StartDate", 'S', "yyyymmdd", 0, "StartDate " }, {"EndDate", 'E', "yyyymmdd", 0, "EndDate " }, - {"ShabanskyHandling",'B', "ShabanskyHandlingStrategy", 0, "Handling strategy for Shabansky orbits. 0 (default) is ignore; 1 halves target I in Shabansky region; 2 rejects any shell with multiple bounce regions."}, {"UseEop", 'e', 0, 0, "Use Earth Orientation Parameters when computing ephemerii" }, {"Force", 'F', 0, 0, "Overwrite output file even if it already exists" }, {"verbose", 'v', "verbosity", 0, "Produce verbose output" }, @@ -80,7 +78,6 @@ struct Arguments { int Quality; int nFLsInDriftShell; int Force; - int ShabanskyHandling; double LT; double FootPointHeight; double Delta; @@ -90,8 +87,8 @@ struct Arguments { int UseEop; - char StartDate[128]; - char EndDate[128]; + long int StartDate; + long int EndDate; }; /* Parse a single option. */ @@ -102,10 +99,10 @@ static error_t parse_opt (int key, char *arg, struct argp_state *state) { struct Arguments *arguments = state->input; switch( key ) { case 'S': // start date - strcpy( arguments->StartDate, arg ); + sscanf( arg, "%ld", &arguments->StartDate ); break; case 'E': // end date - strcpy( arguments->EndDate, arg ); + sscanf( arg, "%ld", &arguments->EndDate ); break; case 'e': // external model strcpy( arguments->ExtModel, arg ); @@ -119,9 +116,6 @@ static error_t parse_opt (int key, char *arg, struct argp_state *state) { case 'F': arguments->Force = 1; break; - case 'B': - arguments->ShabanskyHandling = atoi( arg ); - break; case 'f': sscanf( arg, "%lf", &arguments->FootPointHeight ); break; @@ -168,17 +162,15 @@ static struct argp argp = { Options, parse_opt, ArgsDoc, doc }; int main( int argc, char *argv[] ){ struct Arguments arguments; - double UTC, brac1, brac2, tol, sJD, eJD, JD=LGM_FILL_VALUE; - double jDate, jDate_beg, jDate_end, t_cadence; + double UTC, brac1, brac2, tol, sJD, eJD, JD, jDate, t_cadence; double K[500], LS[500], Kin[500], Bm[500]; - int DOT[500]; double Inc, FootpointHeight, LT; - int Force, UseEop, retval; + int Force, UseEop; int UseTS07=0; - long int Date, currDate; + long int StartDate, EndDate, Date, currDate; int nK, i, Quality, nFLsInDriftShell, ans, aa, Year, Month, Day; char Str[128], NewStr[2048]; - char StartDate[128], EndDate[128], IntModel[20], ExtModel[20]; + char IntModel[20], ExtModel[20]; char Filename[1024]; Lgm_LstarInfo *LstarInfo = InitLstarInfo(0); Lgm_LstarInfo *LstarInfo3; @@ -192,23 +184,22 @@ int main( int argc, char *argv[] ){ /* * Default option values. */ - arguments.StartK = 0.001; // start at 90.0 Deg. - arguments.EndK = 3.0; // stop at 2.5 Deg. - arguments.nK = 18; // 18 pitch angles - arguments.silent = 0; - arguments.verbose = 0; - arguments.Quality = 3; - arguments.nFLsInDriftShell = 96; - arguments.ShabanskyHandling = LGM_SHABANSKY_IGNORE; - arguments.Delta = 30; - arguments.Force = 0; - arguments.LT = 0.0; - arguments.UseEop = 0; - strcpy( arguments.StartDate, "-1" ); - strcpy( arguments.EndDate, "-1" ); - arguments.FootPointHeight = 100.0; // km + arguments.StartK = 0.001; // start at 90.0 Deg. + arguments.EndK = 3.0; // stop at 2.5 Deg. + arguments.nK = 18; // 18 pitch angles + arguments.silent = 0; + arguments.verbose = 0; + arguments.Quality = 3; + arguments.nFLsInDriftShell = 24; + arguments.Delta = 30; + arguments.Force = 0; + arguments.LT = 0.0; + arguments.UseEop = 0; + arguments.StartDate = -1; + arguments.EndDate = -1; + arguments.FootPointHeight = 100.0; // km strcpy( arguments.IntModel, "IGRF" ); - strcpy( arguments.ExtModel, "T89c" ); + strcpy( arguments.ExtModel, "T89" ); /* * Parse CmdLine arguments and options @@ -228,11 +219,6 @@ int main( int argc, char *argv[] ){ } else { Lgm_GeometricSeq( arguments.StartK, arguments.EndK, nK, Kin ); } -//HACK: -nK=3; -Kin[0] = 0.05; -Kin[1] = 0.11; -Kin[2] = 0.2; /* * Set other options @@ -244,14 +230,13 @@ Kin[2] = 0.2; Force = arguments.Force; LT = arguments.LT; UseEop = arguments.UseEop; - strcpy( StartDate, arguments.StartDate ); - strcpy( EndDate, arguments.EndDate ); + StartDate = arguments.StartDate; + EndDate = arguments.EndDate; strcpy( IntModel, arguments.IntModel ); strcpy( ExtModel, arguments.ExtModel ); // Settings for Lstar calcs - LstarInfo->ShabanskyHandling = arguments.ShabanskyHandling; - LstarInfo->ISearchMethod = 2; // 1= Original ROEDERER METHOD (find Bm along ray first); 2= Find Bm by tracing from footpoint along FL. + LstarInfo->ISearchMethod = 2; // 1= Original ROEDERER METHOD (fing Bm along ray first); 2= Find Bm by tracing from footpoint along FL. LstarInfo->VerbosityLevel = arguments.verbose; LstarInfo->mInfo->VerbosityLevel = arguments.verbose; LstarInfo->mInfo->Lgm_LossConeHeight = FootpointHeight; @@ -295,16 +280,12 @@ Kin[2] = 0.2; LstarInfo->mInfo->InternalModel = LGM_IGRF; } - retval = IsoTimeStringToDateTime( StartDate, &DT_UTC, LstarInfo->mInfo->c); - currDate = Lgm_JD_to_Date( jDate, &Year, &Month, &Day, &UTC ); - sJD = DT_UTC.JD; - jDate_beg = (double)((int)(DT_UTC.JD-2400000.5))+2400000.5; //JD for start of first day - jDate_end = (double)((int)(DT_UTC.JD-2400000.5)+1)+2400000.5; //JD for end of first day - retval = IsoTimeStringToDateTime( EndDate, &DT_UTC, LstarInfo->mInfo->c); - eJD = DT_UTC.JD; + sJD = Lgm_Date_to_JD( StartDate, 0.0, LstarInfo->mInfo->c); + eJD = Lgm_Date_to_JD( EndDate, 23.9999, LstarInfo->mInfo->c); - for (jDate = jDate_beg; jDate <= eJD; jDate+= 1.0 ) { + for (jDate = sJD; jDate <= eJD; jDate+= 1.0 ) { + /* * Set output filename, etc. */ @@ -322,8 +303,8 @@ Kin[2] = 0.2; fp = fopen(Filename, "w"); // Bracket Position in GSM - brac1 = -3.0; - brac2 = -15.0; + brac1 = -3.5; + brac2 = -13.0; /* @@ -377,7 +358,7 @@ Kin[2] = 0.2; fprintf(fp, "\"LCDS_%g\" ],\n", Kin[i] ); fprintf( fp, "# \"ELEMENT_LABELS\": [ "); for (i=0; i 0 ) { - fprintf( fp, "# \"ShellType\": { \"DESCRIPTION\": \"Shell Type\",\n"); - fprintf( fp, "# \"NAME\": \"Type\",\n"); - fprintf( fp, "# \"TITLE\": \"Type\",\n"); - fprintf( fp, "# \"LABEL\": \"Type\",\n"); - fprintf( fp, "# \"UNITS\": \"dimensionless\",\n"); - fprintf( fp, "# \"DIMENSION\": [ %d ],\n", nK ); - fprintf( fp, "# \"START_COLUMN\": %d,\n", nCol); nCol += nK; - fprintf( fp, "# \"ELEMENT_NAMES\": [ "); - for (i=0; imInfo->c); @@ -492,15 +449,12 @@ Kin[2] = 0.2; for (aa=0; aaPitchAngle = Alpha[aa]; - if (arguments.verbose >= 1) printf("Date, UTC, aa, Alpha, tol = %ld, %g, %d, %g, %g\n", Date, UTC, aa, LstarInfo3->PitchAngle, tol); + //printf("Date, UTC, aa, Alpha, tol = %ld, %g, %d, %g, %g\n", Date, UTC, aa, LstarInfo3->PitchAngle, tol); ans = Lgm_LCDS( Date, UTC, brac1, brac2, Kin[aa], LT, tol, Quality, nFLsInDriftShell, &K[aa], LstarInfo3 ); - if (LstarInfo3->DriftOrbitType == 1) printf("K: %g; Drift Orbit Type: Closed; L* = %g\n", Kin[aa], LstarInfo3->LS); - if (LstarInfo3->DriftOrbitType == 21) printf("K: %g; Drift Orbit Type: Shabansky_I; L* = %g\n", Kin[aa], LstarInfo3->LS); - if (LstarInfo3->DriftOrbitType == 22) printf("K: %g; Drift Orbit Type: Shabansky_II; L* = %g\n", Kin[aa], LstarInfo3->LS); - DOT[aa] = LstarInfo3->DriftOrbitType; + if (LstarInfo3->DriftOrbitType == 1) printf("K: %g; Drift Orbit Type: Closed; L* = %g \n", Kin[aa], LstarInfo3->LS); + if (LstarInfo3->DriftOrbitType == 2) printf("Drift Orbit Type: Shebansky; L* = %g\n", LstarInfo3->LS); if (ans==0) { LS[aa] = LstarInfo3->LS; Bm[aa] = LstarInfo3->mInfo->Bm; @@ -529,13 +483,10 @@ Kin[2] = 0.2; for ( i=0; i/dev/null` -HDF5_CFLAGS=`pkg-config --cflags hdf5 2>/dev/null` +HDF5_LDFLAGS=`pkg-config --libs dio_hdf5 2>/dev/null` +HDF5_CFLAGS=`pkg-config --cflags dio_hdf5 2>/dev/null` CHECK_LIBS=`pkg-config --libs check 2>/dev/null` CHECK_CFLAGS=`pkg-config --cflags check 2>/dev/null` @@ -380,7 +378,8 @@ AC_CONFIG_FILES([Makefile libLanlGeoMag/EopData/GetEopFiles libLanlGeoMag/lgm.pc lanlgeomag.spec - Tools/Makefile - Python/Makefile + Tools/Makefile + Python/Makefile + Doc/LanlGeoMag.tag ]) AC_OUTPUT diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 000000000..0e47c44ea --- /dev/null +++ b/debian/changelog @@ -0,0 +1,5 @@ +lanlgeomag (1.5.16-1) bionic; urgency=medium + + * Initial release + + -- Mark Galassi Mon, 30 Mar 2020 01:47:03 -0600 diff --git a/debian/compat b/debian/compat new file mode 100644 index 000000000..f599e28b8 --- /dev/null +++ b/debian/compat @@ -0,0 +1 @@ +10 diff --git a/debian/control b/debian/control new file mode 100644 index 000000000..9e2b3b27e --- /dev/null +++ b/debian/control @@ -0,0 +1,25 @@ +Source: lanlgeomag +Priority: optional +Maintainer: Mark Galassi +Build-Depends: debhelper (>= 10), autotools-dev +Standards-Version: 4.1.2 +Section: libs +Homepage: +#Vcs-Git: https://anonscm.debian.org/git/collab-maint/lanlgeomag.git +#Vcs-Browser: https://anonscm.debian.org/cgit/collab-maint/lanlgeomag.git + +Package: lanlgeomag-dev +Section: libdevel +Architecture: any +Multi-Arch: same +Depends: lanlgeomag (= ${binary:Version}), ${misc:Depends} +Description: geomagnetic coordinate library, development files + Mike Henderson's geomagnetic coordinate transformation library, + development files + +Package: lanlgeomag +Architecture: any +Multi-Arch: same +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: geomagnetic coordinate library + Mike Henderson's geomagnetic coordinate transformation library diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 000000000..1b6ee1238 --- /dev/null +++ b/debian/copyright @@ -0,0 +1,29 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: lanlgeomag +Source: https://github.com/markgalassi/LANLGeoMag + +Files: * +Copyright: Los Alamos National Laboratory 2010-2020 Michael Henderson + +License: GPL-3.0+ + +Files: debian/* +Copyright: 2020 Mark Galassi +License: GPL-3.0+ + +License: GPL-3.0+ + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + . + This package is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + . + You should have received a copy of the GNU General Public License + along with this program. If not, see . + . + On Debian systems, the complete text of the GNU General + Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". diff --git a/debian/files b/debian/files new file mode 100644 index 000000000..075e50c95 --- /dev/null +++ b/debian/files @@ -0,0 +1,4 @@ +lanlgeomag-dbgsym_1.5.16-1_amd64.ddeb debug optional +lanlgeomag-dev_1.5.16-1_amd64.deb libdevel optional +lanlgeomag_1.5.16-1_amd64.buildinfo libs optional +lanlgeomag_1.5.16-1_amd64.deb libs optional diff --git a/debian/lanlgeomag-dev.dirs b/debian/lanlgeomag-dev.dirs new file mode 100644 index 000000000..995e528a1 --- /dev/null +++ b/debian/lanlgeomag-dev.dirs @@ -0,0 +1,3 @@ +usr/lib +usr/include +usr/share diff --git a/debian/lanlgeomag-dev.install b/debian/lanlgeomag-dev.install new file mode 100644 index 000000000..f9379d549 --- /dev/null +++ b/debian/lanlgeomag-dev.install @@ -0,0 +1,3 @@ +usr/include/* +usr/lib/*/lib*.so +usr/share/pkgconfig/* diff --git a/debian/lanlgeomag.dirs b/debian/lanlgeomag.dirs new file mode 100644 index 000000000..f7077cffb --- /dev/null +++ b/debian/lanlgeomag.dirs @@ -0,0 +1,2 @@ +usr/lib +usr/share diff --git a/debian/lanlgeomag.install b/debian/lanlgeomag.install new file mode 100644 index 000000000..d6f4b0aa4 --- /dev/null +++ b/debian/lanlgeomag.install @@ -0,0 +1,2 @@ +usr/lib/*/lib*.so.* +usr/share/LanlGeoMag/* diff --git a/debian/rules b/debian/rules new file mode 100755 index 000000000..e1c367c12 --- /dev/null +++ b/debian/rules @@ -0,0 +1,25 @@ +#!/usr/bin/make -f +# See debhelper(7) (uncomment to enable) +# output every command that modifies files on the build system. +#export DH_VERBOSE = 1 + + +# see FEATURE AREAS in dpkg-buildflags(1) +#export DEB_BUILD_MAINT_OPTIONS = hardening=+all + +# see ENVIRONMENT in dpkg-buildflags(1) +# package maintainers to append CFLAGS +#export DEB_CFLAGS_MAINT_APPEND = -Wall -pedantic +# package maintainers to append LDFLAGS +#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed + + +%: + dh $@ + + +# dh_make generated override targets +# This is example for Cmake (See https://bugs.debian.org/641051 ) +#override_dh_auto_configure: +# dh_auto_configure -- # -DCMAKE_LIBRARY_PATH=$(DEB_HOST_MULTIARCH) + diff --git a/debian/source/format b/debian/source/format new file mode 100644 index 000000000..163aaf8d8 --- /dev/null +++ b/debian/source/format @@ -0,0 +1 @@ +3.0 (quilt) diff --git a/lanlgeomag.spec.in b/lanlgeomag.spec.in index e4dd9b97a..951d560d2 100644 --- a/lanlgeomag.spec.in +++ b/lanlgeomag.spec.in @@ -1,31 +1,70 @@ %define debug_package %{nil} +%global __python /usr/bin/python3 +%global clamp_mtime_to_source_date_epoch 0 +%global source_date_epoch_from_changelog 0 %define name @PACKAGE@ %define version @VERSION@ %define release @PKG_RELEASE@ -## make sure you define _topdir as $HOME/rpmbuild in your .rpmmacros -#%global buildroot %{_topdir}/BUILDROOT Summary: lanlgeomag -- lanlgeomag software collection License: Copyright (C) 2010, LANS LLC, all rights reserved. Name: %{name} Version: %{version} Release: %{release}%{?dist} +BuildRequires: texlive-latex +BuildRequires: gsl +BuildRequires: doxygen Provides: lanlgeomag -Requires: perl +#Requires: perl Requires: check Requires: gsl -Requires: hdf5 Source: %{name}-%{version}.tar.gz -Prefix: /usr Group: Applications/Science Provides: lanlgeomag Buildroot: %{_topdir}/BUILDROOT/%{name}-%{version}-%{release}.%{_arch} buildroot: %{_topdir}/BUILDROOT/%{name}-%{version}-%{release}.%{_arch} %description -LANLGeoMag is a C-based library of magnetic-field models and tools for computing quantities relevant to geophysical and geospace research that rely on these models. -More generally, the library provides functionality to perform high precision transforms between time standards and coordinate systems. +LANLGeoMag is a C-based library of magnetic-field models and tools for \ +computing quantities relevant to geophysical and geospace research that rely \ +on these models. More generally, the library provides functionality to perform \ +high precision transforms between time standards and coordinate systems. + +%package devel +Summary: Development libraries and headers for lanlgeomag +Requires: lanlgeomag + +%description devel +Development libraries and headers for lanlgeomag + +%package data +Summary: Data files for lanlgeomag +Requires: lanlgeomag + +%description data +Data files for lanlgeomag + +%package doc +Summary: Doc files for lanlgeomag +Requires: lanlgeomag + +%description doc +Doc files for lanlgeomag + +%package python +Summary: Python bindings for lanlgeomag +Requires: lanlgeomag + +%description python +Python bindings for lanlgeomag + +# %package images +# Summary: Image files for lanlgeomag +# Requires: lanlgeomag + +# %description images +# Image files for lanlgeomag %prep mkdir -p %{_topdir}/BUILD %{_topdir}/BUILDROOT @@ -38,34 +77,51 @@ echo "__isa_bits is" "%{__isa_bits}" %setup -q %build -#./configure --prefix=/usr --disable-doxygen-html --disable-doxygen-pdf -%configure --libdir=${RPM_BUILD_ROOT}%{_libdir} --prefix=${RPM_BUILD_ROOT}/usr --enable-doxygen-doc --enable-doxygen-pdf -make -j +echo "python_sitelib:" +echo %{python_sitelib} +%configure --enable-doxygen-doc --enable-doxygen-pdf --disable-perl +make %{?_smp_mflags} || true +make %install -#export RPM_BUILD_ROOT=%{_topdir}/BUILDROOT/%{name}-%{version}-%{release}.%{_arch} -#export RPM_BUILD_ROOT=%{_topdir}/BUILDROOT -echo _topdir is %{_topdir} -echo RPM_BUILD_ROOT is $RPM_BUILD_ROOT -echo buildroot is %{buildroot} -echo _builddir is %{_builddir} -#make prefix=${RPM_BUILD_ROOT}/usr install %makeinstall -#make install -#make install-man -#make doxygen-doc -#mkdir -p %{buildroot}/share/doc/%{name} -#cp -p doxygen-doc/lanlgeomag.pdf %{buildroot}/share/doc/%{name} %clean -/bin/rm -rf $RPM_BUILD_ROOT +#/bin/rm -rf $RPM_BUILD_ROOT %files %defattr(-,root,root) -#%doc README HACKING NEWS COPYING -/usr/include/Lgm/* -/usr/lib64/libLanlGeoMag* -/usr/lib64/pkgconfig/lgm.pc -/usr/lib/python2.6/site-packages/lgmpy/* -/usr/share/LanlGeoMag/* +%doc README.md HACKING NEWS COPYING +%defattr(-,root,root,-) +%{_libdir}/*.so.* +%{_libdir}/pkgconfig/lgm.pc + + +%files devel +%defattr(-,root,root,-) +%{_includedir}/* +%{_libdir}/*.so* +%{_libdir}/*.*a +%{_docdir}/* + +%files data +%defattr(-,root,root,-) +%{_datadir}/* +# /usr/share/LanlGeoMag/EopData/* +# /usr/share/LanlGeoMag/Data/* + +%files doc +%defattr(-,root,root,-) /usr/share/doc/lanlgeomag/* + +#files python +#defattr(-,root,root,-) + +#{python_sitelib}/* + + +#{_includedir}/Lgm/* +#{_libdir}/libLanlGeoMag* +#{_libdir}/pkgconfig/lgm.pc +#/usr/lib/python2.6/site-packages/lgmpy/* +#{_datadir}/* diff --git a/libLanlGeoMag/ComputeI_FromMltMlat.c b/libLanlGeoMag/ComputeI_FromMltMlat.c index c1c1f634b..408cbf58e 100644 --- a/libLanlGeoMag/ComputeI_FromMltMlat.c +++ b/libLanlGeoMag/ComputeI_FromMltMlat.c @@ -52,7 +52,7 @@ double ComputeI_FromMltMlat1( double Bm, double MLT, double mlat, double *r, dou * Couldnt get a valid Bm. (The bracket is pretty huge,so * we probably ought to believe there really isnt a valid one.) */ - if (LstarInfo->VerbosityLevel > 1) printf("\t%sNo Bm found: setting I to 9e99%s\n", LstarInfo->PreStr, LstarInfo->PostStr); + if (LstarInfo->VerbosityLevel > 0) printf("\t%sNo Bm found: setting I to 9e99%s\n", LstarInfo->PreStr, LstarInfo->PostStr); I = 9e99; } else { @@ -136,6 +136,7 @@ double ComputeI_FromMltMlat1( double Bm, double MLT, double mlat, double *r, dou sgn = 1.0; } else { // we are probably very close to Pmin. So I=0. +//printf("DFSsssssssssssssssssssssssS\n"); LstarInfo->mInfo->Pm_North = Pmirror1; LstarInfo->mInfo->Pm_South = Pmirror1; return( 0.0 ); diff --git a/libLanlGeoMag/ComputeLstar.c b/libLanlGeoMag/ComputeLstar.c index d4c0613ee..d16cd321d 100644 --- a/libLanlGeoMag/ComputeLstar.c +++ b/libLanlGeoMag/ComputeLstar.c @@ -65,7 +65,6 @@ int ClassifyFL( int k, Lgm_LstarInfo *LstarInfo ) { */ nMinima = 0; nMaxima = 0; - nBounceRegions=0; Diff = LGM_FILL_VALUE; for ( i=1; inPnts; i++ ){ @@ -91,7 +90,7 @@ int ClassifyFL( int k, Lgm_LstarInfo *LstarInfo ) { if ( nMinima > 1 ) { if ( nMinima >= LGM_LSTARINFO_MAX_MINIMA-1 ) { - printf("\t\tThis Field line has multiple minima (at least %d minima detected). Probably on a bizarre field line (TS04 model?)\n", nMinima ); + printf("\t\tThis Field line has multiple minima (at least %d minima detected). Probably on a bizzare field line (TS04 model?)\n", nMinima ); } else { printf("\t\tThis Field line has multiple minima (%d minima detected). Probably on Shabansky orbit!\n", nMinima ); } @@ -105,7 +104,7 @@ int ClassifyFL( int k, Lgm_LstarInfo *LstarInfo ) { if ( nMaxima > 1 ) { if ( nMinima >= LGM_LSTARINFO_MAX_MINIMA-1 ) { - printf("\t\tThis Field line has multiple maxima (at least %d maxima detected). Probably on a bizarre field line (TS04 model?)\n", nMaxima ); + printf("\t\tThis Field line has multiple maxima (at least %d maxima detected). Probably on a bizzare field line (TS04 model?)\n", nMaxima ); } else { printf("\t\tThis Field line has multiple maxima (%d minima detected excluding endpoints). Probably on Shabansky orbit!\n", nMaxima ); } @@ -137,6 +136,7 @@ int ClassifyFL( int k, Lgm_LstarInfo *LstarInfo ) { } else if ( (nMinima == 2) && (nMaxima == 1) && (iMinima[0] < iMaxima[0]) && (iMinima[1] > iMaxima[0]) ) { // typical expected case for Shab. + nBounceRegions = 0; if ( Maxima[0] < m->Bm ) { // can only bounce in 1 region. @@ -152,7 +152,7 @@ int ClassifyFL( int k, Lgm_LstarInfo *LstarInfo ) { Type = ( nBounceRegions > 0 ) ? nBounceRegions : -8; - } else if ( nMinima > LGM_LSTARINFO_MAX_MINIMA-5 ) { // way too many minima -- bad/bizarre FL (TS04 seems to give these?) + } else if ( nMinima > LGM_LSTARINFO_MAX_MINIMA-5 ) { // way too many minima -- bad/bizzare FL (TS04 seems to give these?) Type = -1; @@ -162,9 +162,9 @@ int ClassifyFL( int k, Lgm_LstarInfo *LstarInfo ) { * OK, there are more than 2 minima. Loop over them and determine how * many separate regions on the FL we can mirror on. If there is only * one, then we should be a Type 1 Shabansky orbit (i.e. no - * bifurcation, but still have multiple minima). + * biffurcation, but still have multiple minima). * Count up how many cases we have where; - * 1) a maximum exceeds the Bm values. + * 1) a maxima exceeds the Bm values. * 2) minima that drop below Bm on either side. * The number of mirroring regions should be this number plus one. */ @@ -175,7 +175,7 @@ int ClassifyFL( int k, Lgm_LstarInfo *LstarInfo ) { } } - Type = nBounceRegions; +Type = nBounceRegions; } @@ -190,6 +190,7 @@ int ClassifyFL( int k, Lgm_LstarInfo *LstarInfo ) { //} +//if (Type > 0 ) printf("Type = %d\n", Type); return( Type ); @@ -221,14 +222,16 @@ void Lgm_SetLstarTolerances( int Quality, int nFLsInDriftShell, Lgm_LstarInfo *s s->LstarQuality = Quality; } - if ( ( nFLsInDriftShell < 6 ) || ( nFLsInDriftShell > 240 ) ) { - printf("%sLgm_SetLstarTolerances: nFLsInDriftShell value (of %d) not in range [6, 240]. Setting to 24.%s\n", s->PreStr, nFLsInDriftShell, s->PostStr ); + if ( ( nFLsInDriftShell < 0 ) || ( nFLsInDriftShell > 240 ) ) { + printf("%sLgm_SetLstarTolerances: nFLsInDriftShell value (of %d) not in range [0, 240]. Setting to 24.%s\n", s->PreStr, nFLsInDriftShell, s->PostStr ); s->nFLsInDriftShell = 24; } else { s->nFLsInDriftShell = nFLsInDriftShell; } // These tend to be critical to keep things working smoothly. +// s->mInfo->Lgm_FindBmRadius_Tol = 1e-10; +// s->mInfo->Lgm_TraceToMirrorPoint_Tol = 1e-10; s->mInfo->Lgm_FindBmRadius_Tol = 1e-10; s->mInfo->Lgm_TraceToMirrorPoint_Tol = 1e-10; @@ -438,22 +441,21 @@ Lgm_LstarInfo *InitLstarInfo( int VerbosityLevel ) { Lgm_LstarInfo *LstarInfo; + /* * Allocate memory for LstarInfo structure */ LstarInfo = (Lgm_LstarInfo *) calloc( 1, sizeof( *LstarInfo)); + + + /* * Allocate memory for mInfo structure inside the LstarInfo structure. */ LstarInfo->mInfo = Lgm_InitMagInfo( ); Lgm_InitLstarInfoDefaults(LstarInfo); - if ( (VerbosityLevel >= 0) && (VerbosityLevel <=8) ){ - LstarInfo->VerbosityLevel = VerbosityLevel; - } else { - printf( "InitLstarInfo: Verbosity not in range [0,9] (Got %d). Using default value (%d)).\n", VerbosityLevel, LstarInfo->VerbosityLevel ); - } return(LstarInfo); } @@ -465,8 +467,6 @@ void Lgm_InitLstarInfoDefaults( Lgm_LstarInfo *LstarInfo ) { LstarInfo->VerbosityLevel = 2; LstarInfo->LSimpleMax = 10.0; LstarInfo->ISearchMethod = 1; - LstarInfo->ShabanskyHandling = LGM_SHABANSKY_IGNORE; - LstarInfo->LstarMoment = LGM_LSTAR_MOMENT_CDIP_2010; LstarInfo->PreStr[0] = '\0'; LstarInfo->PostStr[0] = '\0'; @@ -567,41 +567,36 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ Lgm_Vector u, v, w, v1, v2, v3, Bvec, uu; - int i, j, k, nk, nLines, koffset, tkk, nfp, nnn, doExit=FALSE; - int done2, Count, FoundShellLine, nIts, Type, retEarthTrace; - int nShabI = 0, nShabII = 0; + int i, j, k, nk, nLines, koffset, tkk, nfp, nnn; + int done2, Count, FoundShellLine, nIts, Type; double rat, B, dSa, dSb, smax, SS, L, Hmax, epsabs, epsrel; - double I=-999.9, Ifound, M, MLT0, MLT, DeltaMLT, mlat, r, sa, sa2; + double I=-999.9, Ifound, M, MLT0, MLT, DeltaMLT, mlat, r; double Phi, Phi1, Phi2, sl, cl, MirrorMLT[3*LGM_LSTARINFO_MAX_FL], MirrorMlat[3*LGM_LSTARINFO_MAX_FL], pred_mlat, mlat_try, pred_delta_mlat=0.0, mlat0, mlat1, delta; double MirrorMLT_Old[3*LGM_LSTARINFO_MAX_FL], MirrorMlat_Old[3*LGM_LSTARINFO_MAX_FL], res; char *PreStr, *PostStr; Lgm_MagModelInfo *mInfo2; +// FILE *fp; PreStr = LstarInfo->PreStr; PostStr = LstarInfo->PostStr; double PredMinusActualMlat = 0.0; - // set dipole moment to use for Lstar calc (in normalization only) - switch(LstarInfo->LstarMoment) { - case LGM_LSTAR_MOMENT_CDIP : - LstarInfo->Mused = LstarInfo->mInfo->c->M_cd; - break; - case LGM_LSTAR_MOMENT_CDIP_2010 : - LstarInfo->Mused = LstarInfo->mInfo->c->M_cd_2010; - break; - case LGM_LSTAR_MOMENT_MCILWAIN : - LstarInfo->Mused = LstarInfo->mInfo->c->M_cd_McIlwain; - break; - default : - LstarInfo->Mused = LstarInfo->mInfo->c->M_cd_2010; - } - /* * Initialize some values to FILL in case we bail early */ LstarInfo->LS = LGM_FILL_VALUE; - LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_OPEN; + + + if (LstarInfo->VerbosityLevel > 1) { + printf("\n\n\t\t%s Computing L* for, Date: %ld, UT: %g%s\n", PreStr, LstarInfo->mInfo->c->UTC.Date, LstarInfo->mInfo->c->UTC.Time, PostStr ); + printf( "\t\t%s=========================================================================%s\n", PreStr, PostStr ); + printf( "\t\t%sDate (yyyymmdd): %ld%s\n", PreStr, LstarInfo->mInfo->c->UTC.Date, PostStr ); + printf( "\t\t%sUTC (hours): %g%s\n", PreStr, LstarInfo->mInfo->c->UTC.Time, PostStr ); + printf( "\t\t%sPitch Angle (deg.): %g%s\n", PreStr, LstarInfo->PitchAngle, PostStr ); + printf( "\t\t%sInitial Position, vin (Re): < %g, %g, %g >%s\n", PreStr, vin->x, vin->y, vin->z, PostStr); + printf( "\t\t%sMirror Mag. Field Strength, Bm (nT): %g%s\n", PreStr, LstarInfo->mInfo->Bm, PostStr ); + } LstarInfo->nPnts = 0; @@ -618,11 +613,11 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ * Do Initial field Line to get Bm and I */ u = *vin; - LstarInfo->mInfo->Bfield( &u, &Bvec, LstarInfo->mInfo ); - LstarInfo->mInfo->Blocal = Lgm_Magnitude( &Bvec ); if (LstarInfo->VerbosityLevel > 1) { printf("\n\t\t%sInitial Position, U_gsm (Re): < %g, %g, %g >%s\n", PreStr, u.x, u.y, u.z, PostStr); - printf("\t\t%sMag. Field Strength, B at U_gsm (nT): %g%s\n", PreStr, LstarInfo->mInfo->Blocal, PostStr); + LstarInfo->mInfo->Bfield( &u, &Bvec, LstarInfo->mInfo ); + B = Lgm_Magnitude( &Bvec ); + printf("\t\t%sMag. Field Strength, B at U_gsm (nT): %g%s\n", PreStr, B, PostStr); } if ( Lgm_Trace( &u, &v1, &v2, &v3, LstarInfo->mInfo->Lgm_LossConeHeight, TRACE_TOL, TRACE_TOL, LstarInfo->mInfo ) == LGM_CLOSED ) { @@ -630,25 +625,13 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ LstarInfo->d2B_ds2 = LstarInfo->mInfo->d2B_ds2; // second derivative of B wrt s at equator. LstarInfo->RofC = LstarInfo->mInfo->d2B_ds2; // radius of curvature at Bmin point. - sa = sin( LstarInfo->PitchAngle*RadPerDeg ); sa2 = sa*sa; - LstarInfo->mInfo->Bm = LstarInfo->mInfo->Blocal/sa2; // set Bmirror for supplied location, pitch angle, field model, etc. - - if (LstarInfo->VerbosityLevel > 1) { + if (LstarInfo->VerbosityLevel > 1) { printf("\n\t\t%sMin-B Point Location, Pmin (Re): < %g, %g, %g >%s\n", PreStr, LstarInfo->mInfo->Pmin.x, LstarInfo->mInfo->Pmin.y, LstarInfo->mInfo->Pmin.z, PostStr); - LstarInfo->mInfo->Bfield( &u, &Bvec, LstarInfo->mInfo ); - B = Lgm_Magnitude( &Bvec ); + LstarInfo->mInfo->Bfield( &u, &Bvec, LstarInfo->mInfo ); + B = Lgm_Magnitude( &Bvec ); printf("\t\t%sMag. Field Strength, B at Pmin (nT): %g%s\n", PreStr, B, PostStr); } - if (LstarInfo->VerbosityLevel > 0) { - printf("\n\n\t\t%s Computing L* for, Date: %ld, UT: %g%s\n", PreStr, LstarInfo->mInfo->c->UTC.Date, LstarInfo->mInfo->c->UTC.Time, PostStr ); - printf( "\t\t%s=========================================================================%s\n", PreStr, PostStr ); - printf( "\t\t%sDate (yyyymmdd): %ld%s\n", PreStr, LstarInfo->mInfo->c->UTC.Date, PostStr ); - printf( "\t\t%sUTC (hours): %g%s\n", PreStr, LstarInfo->mInfo->c->UTC.Time, PostStr ); - printf( "\t\t%sPitch Angle (deg.): %g%s\n", PreStr, LstarInfo->PitchAngle, PostStr ); - printf( "\t\t%sInitial Position, vin (Re): < %g, %g, %g >%s\n", PreStr, vin->x, vin->y, vin->z, PostStr); - printf( "\t\t%sMirror Mag. Field Strength, Bm (nT): %g%s\n", PreStr, LstarInfo->mInfo->Bm, PostStr ); - } /* * If we are here, we know the field line is closed. */ @@ -661,6 +644,7 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ * Shabansky drift orbit type bifurcations.) * */ +//// DAMN!!!!!!!!!!!!!!!!!!!1 //This wont work! //you need to trace the FL with TraceLine for ClassifyFL() to work!!!!!!!!!!!!! // Type = ClassifyFL( 0, LstarInfo ); @@ -698,6 +682,8 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ } + + /* * Set the limits of integration. Define s=0 at the sourthern mirror point. Then, sm_North will just be dSb */ @@ -737,10 +723,16 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ /* * Do interped I integral. */ +// epsabs = LstarInfo->mInfo->Lgm_I_Integrator_epsabs; +// epsrel = LstarInfo->mInfo->Lgm_I_Integrator_epsrel; +// LstarInfo->mInfo->Lgm_I_Integrator_epsabs /= 10.0; +// LstarInfo->mInfo->Lgm_I_Integrator_epsrel /= 10.0; I = Iinv_interped( LstarInfo->mInfo ); if (LstarInfo->VerbosityLevel > 1) { printf("\t\t %sIntegral Invariant, I (interped): %g%s\n", PreStr, I, PostStr ); } +// LstarInfo->mInfo->Lgm_I_Integrator_epsabs = epsabs; +// LstarInfo->mInfo->Lgm_I_Integrator_epsrel = epsrel; /* * Do interped Sb integral if desired. Note this is @@ -757,11 +749,19 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ printf("\t\t %sSb Integral, (interped): %g%s\n", PreStr, LstarInfo->SbIntegral0, PostStr ); } } + + + FreeSpline( LstarInfo->mInfo ); + } else { + I = LGM_FILL_VALUE; + } + + } else { /* @@ -775,14 +775,20 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ LstarInfo->I0 = I; // save initial I in LstarInfo structure. Ifound = I; + + if (LstarInfo->VerbosityLevel > 1) { + // sort this out. FIX User should decide what M they want to use. + //M = LstarInfo->mInfo->c->M_cd; + //M = LstarInfo->mInfo->c->M_cd_McIllwain; + M = LstarInfo->mInfo->c->M_cd_2010; printf("\t\t %sLgm_n_I_integrand_Calls: %d%s\n\n", PreStr, LstarInfo->mInfo->Lgm_n_I_integrand_Calls, PostStr ); printf("\t\t%sCurrent Dipole Moment, M_cd: %g%s\n", PreStr, LstarInfo->mInfo->c->M_cd, PostStr); - printf("\t\t%sReference Dipole Moment, M_cd_McIlwain: %g%s\n", PreStr, LstarInfo->mInfo->c->M_cd_McIlwain, PostStr); + printf("\t\t%sReference Dipole Moment, M_cd_McIllwain: %g%s\n", PreStr, LstarInfo->mInfo->c->M_cd_McIllwain, PostStr); printf("\t\t%sReference Dipole Moment, M_cd_2010: %g%s\n", PreStr, LstarInfo->mInfo->c->M_cd_2010, PostStr); - printf("\t\t%sDipole Moment Used, Mused: %g%s\n", PreStr, LstarInfo->Mused, PostStr); - printf("\t\t%sMcIlwain L (Hilton): %.15g%s\n", PreStr, L = LFromIBmM_Hilton( I, LstarInfo->mInfo->Bm, LstarInfo->Mused ), PostStr ); - printf("\t\t%sMcIlwain L (McIlwain): %.15g%s\n", PreStr, L = LFromIBmM_McIlwain( I, LstarInfo->mInfo->Bm, LstarInfo->Mused ), PostStr ); + printf("\t\t%sDipole Moment Used, Mused: %g%s\n", PreStr, M, PostStr); + printf("\t\t%sMcIlwain L (Hilton): %.15g%s\n", PreStr, L = LFromIBmM_Hilton( I, LstarInfo->mInfo->Bm, M ), PostStr ); + printf("\t\t%sMcIlwain L (McIlwain): %.15g%s\n", PreStr, L = LFromIBmM_McIlwain( I, LstarInfo->mInfo->Bm, M ), PostStr ); } } else { @@ -808,15 +814,27 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ + + + /* * If we get here, then the field line going through our starting point is * closed and we could find the required mirror points. */ + + + + // initialize DriftOrbitType as open + //for ( i=0; inMinima[i] > 1 ) LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_OPEN; + //for ( i=0; iDriftOrbitType = LGM_DRIFT_ORBIT_OPEN; + + + /* * Construct drift shell. Get a good initial estimate for mlat */ - if ( LstarInfo->ISearchMethod == 1 ) { + if ( LstarInfo->ISearchMethod == 1 ) { // this method uses the mlat as the mlat of the mirror point. Lgm_Convert_Coords( &LstarInfo->mInfo->Pm_North, &u, GSM_TO_SM, LstarInfo->mInfo->c ); @@ -835,6 +853,7 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ MLT0 = atan2( u.y, u.x )*DegPerRad/15.0 + 12.0; if (LstarInfo->VerbosityLevel > 2) printf("\t\t%smlat = %g%s\n", PreStr, mlat, PostStr ); + LstarInfo->nPnts = 0; pred_delta_mlat = 0.0; for (k=0; k<3*LGM_LSTARINFO_MAX_FL; ++k){ MirrorMLT[k] = 0.0; @@ -842,6 +861,7 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ } + nLines = LstarInfo->nFLsInDriftShell; DeltaMLT = 24.0/((double)nLines); @@ -897,108 +917,118 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ * mlat. If this doesnt work, we expand the size of the range. * */ - done2 = FALSE; FoundShellLine = FALSE; Count = 0; + done2 = FALSE; FoundShellLine = FALSE; Count = 0; LstarInfo->nImI0 = 0; while ( !done2 && (k > 0) ) { if ( Count == 0 ) { - /* - * First time through -- lets use the predicted range. - */ - //mlat0 = ((pred_mlat-delta) < 0.0) ? 0.0 : (pred_mlat-delta); - if (delta > 20.0) delta = 20.0; + /* + * First time through -- lets use the predicted range. + */ + //mlat0 = ((pred_mlat-delta) < 0.0) ? 0.0 : (pred_mlat-delta); + if (delta > 20.0) delta = 20.0; - mlat0 = pred_mlat-delta; - mlat_try = pred_mlat; - mlat1 = pred_mlat+delta; + mlat0 = pred_mlat-delta; + mlat_try = pred_mlat; + mlat1 = pred_mlat+delta; - } else if ( Count == 1 ) { + } else if ( Count == 1 ) { - /* - * Perhaps our bracket was no good -- too narrow. Enlarge it. - * Try double what we had. - */ - delta *= 2; - if (delta < 1.0) delta = 1.0; - mlat0 = pred_mlat-delta; - mlat_try = pred_mlat; - mlat1 = pred_mlat+delta; - - if ( LstarInfo->nImI0 > 2 ) { - for (i=0; inImI0; i++) LstarInfo->Earr[i] = 1.0; - //FitQuadAndFindZero2( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, 4, &res ); - FitQuadAndFindZero( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, &res ); - if (LstarInfo->VerbosityLevel > 1){ - printf("\t\t\t1> Fitting to available values. Predicted mlat: %g\n", res ); - } - if ( fabs(res) < 90.0 ){ - mlat_try = res; - mlat0 = res-1.0; - mlat1 = res+1.0; - } + /* + * Perhaps our bracket was no good -- too narrow. Enlarge it. + * Try double what we had. + */ + delta *= 2; + if (delta < 1.0) delta = 1.0; + mlat0 = pred_mlat-delta; + mlat_try = pred_mlat; + mlat1 = pred_mlat+delta; + + if ( LstarInfo->nImI0 > 2 ) { + for (i=0; inImI0; i++) LstarInfo->Earr[i] = 1.0; + //FitQuadAndFindZero2( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, 4, &res ); + //FitLineAndFindZero( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, &res ); + FitQuadAndFindZero( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, &res ); + if (LstarInfo->VerbosityLevel > 1){ + printf("\t\t\t1> Fitting to available values. Predicted mlat: %g\n", res ); + } + if ( fabs(res) < 90.0 ){ + mlat_try = res; + mlat0 = res-1.0; + mlat1 = res+1.0; } + } + - } else if ( Count == 2 ) { + } else if ( Count == 2 ) { /* * Hmmm... This ones stuborn! Lets be more conservative now. * Try +1/-5 around the returned mlat */ - //if ( FoundShellLine == -3 ) { - // mlat0 = ((mlat-5.0) > -10.0) ? -10.0 : (mlat-5.0); - // mlat1 = ((mlat+1.0) > 90.0) ? 90.0 : (mlat+1.0); - //} else { - // mlat0 = ((mlat-1.0) > -10.0) ? -10.0 : (mlat-1.0); - // mlat1 = ((mlat+5.0) > 90.0) ? 90.0 : (mlat+5.0); - /// } - mlat_try = pred_mlat; - mlat0 = mlat_try-5.0; - mlat1 = mlat_try+1.0; - - if ( LstarInfo->nImI0 > 3 ) { - for (i=0; inImI0; i++) LstarInfo->Earr[i] = 1.0; - //FitQuadAndFindZero2( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, 4, &res ); - FitQuadAndFindZero( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, &res ); - if (LstarInfo->VerbosityLevel > 1){ - printf("\t\t\t2> Fitting to available values. Predicted mlat: %g\n", res ); - } - if ( fabs(res) < 90.0 ){ - mlat_try = res; - mlat0 = res-5.0; - mlat1 = res+5.0; - } + //if ( FoundShellLine == -3 ) { + // mlat0 = ((mlat-5.0) > -10.0) ? -10.0 : (mlat-5.0); + // mlat1 = ((mlat+1.0) > 90.0) ? 90.0 : (mlat+1.0); + //} else { + // mlat0 = ((mlat-1.0) > -10.0) ? -10.0 : (mlat-1.0); + // mlat1 = ((mlat+5.0) > 90.0) ? 90.0 : (mlat+5.0); + //// } + mlat_try = pred_mlat; + mlat0 = mlat_try-5.0; + mlat1 = mlat_try+1.0; + + if ( LstarInfo->nImI0 > 3 ) { + for (i=0; inImI0; i++) LstarInfo->Earr[i] = 1.0; + //FitQuadAndFindZero2( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, 4, &res ); + FitQuadAndFindZero( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, &res ); + if (LstarInfo->VerbosityLevel > 1){ + printf("\t\t\t2> Fitting to available values. Predicted mlat: %g\n", res ); + } + if ( fabs(res) < 90.0 ){ + mlat_try = res; + mlat0 = res-5.0; + mlat1 = res+5.0; } + } - } else { - /* - * OK, there may not be a good line -- i.e. drift shell may not be closed. - * To make sure, lets try 0->90 deg. - */ - mlat0 = 0.0; //mlat0 = -60.0; - mlat_try = pred_mlat; - mlat1 = 90.0; -// mlat1 = 45.0; //what is a good alternate here? 75? 80? 85? - - if ( (LstarInfo->nImI0 > 3) && (LstarInfo->nImI0%4 == 0) ){ - for (i=0; inImI0; i++) LstarInfo->Earr[i] = 1.0; - //FitQuadAndFindZero2( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, 4, &res ); - FitQuadAndFindZero( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, &res ); - if (LstarInfo->VerbosityLevel > 1){ - printf("\t\t\t3> Fitting to available values. Predicted mlat: %g\n", res ); - } - if ( fabs(res) < 90.0 ){ - mlat_try = res; - mlat0 = res-45.0; - mlat1 = res+45.0; - } - } + } else { + /* + * OK, there may not be a good line -- i.e. drift shell may not be closed. + * To make sure, lets try 0->90 deg. + */ + //mlat0 = 0.0; + mlat_try = pred_mlat; + mlat0 = -60.0; +//mlat0 = 0.0; + mlat1 = 90.0; +//mlat1 = 45.0; +//mlat1 = 23.855537644144878; + + + +//printf("?? LstarInfo->nImI0 = %d\n", LstarInfo->nImI0); + if ( (LstarInfo->nImI0 > 3) && (LstarInfo->nImI0%4 == 0) ){ + for (i=0; inImI0; i++) LstarInfo->Earr[i] = 1.0; + //FitQuadAndFindZero2( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, 4, &res ); + FitQuadAndFindZero( LstarInfo->MLATarr, LstarInfo->ImI0arr, LstarInfo->Earr, LstarInfo->nImI0, &res ); + if (LstarInfo->VerbosityLevel > 1){ + printf("\t\t\t3> Fitting to available values. Predicted mlat: %g\n", res ); + } + if ( fabs(res) < 90.0 ){ + mlat_try = res; + mlat0 = res-45.0; + mlat1 = res+45.0; + } } + } + + if (LstarInfo->VerbosityLevel > 1) { printf("\n\t\t%s________________________________________________________________________________________________________________________________%s\n\n", PreStr, PostStr ); printf("\t\t%s Field Line %02d of %02d MLT: %g (Predicted mlat: %g %g %g delta: %g) Count: %d %s\n", PreStr, k+1, nLines, MLT, mlat0, pred_mlat, mlat1, delta, Count, PostStr ); @@ -1006,122 +1036,95 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ } FoundShellLine = FindShellLine( I, &Ifound, LstarInfo->mInfo->Bm, MLT, &mlat, &r, mlat0, mlat_try, mlat1, &nIts, LstarInfo ); - if (FoundShellLine > 0) { - // Found valid FL for drift shell - done2 = TRUE; - v = LstarInfo->mInfo->Pm_North; - LstarInfo->mInfo->Hmax = 0.1; - retEarthTrace = Lgm_TraceToSphericalEarth( &v, &w, LstarInfo->mInfo->Lgm_LossConeHeight, 1, 1e-9, LstarInfo->mInfo ); - if ( !retEarthTrace ){ - for ( i=0; inPnts; ++i ) if ( LstarInfo->nMinima[i] > 1 ) LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_OPEN_SHABANSKY; - break;//return(-4); - } - - - LstarInfo->Spherical_Footprint_Pn[k] = w; - LstarInfo->mInfo->Hmax = 0.05; - + + + + + + +v = LstarInfo->mInfo->Pm_North; +LstarInfo->mInfo->Hmax = 0.1; +if ( !Lgm_TraceToSphericalEarth( &v, &w, LstarInfo->mInfo->Lgm_LossConeHeight, 1.0, 1e-9, LstarInfo->mInfo ) ){ return(-4); } +LstarInfo->Spherical_Footprint_Pn[k] = w; +LstarInfo->mInfo->Hmax = 0.05; +//Lgm_Vector puke; +//Lgm_Convert_Coords( &LstarInfo->mInfo->Pm_North, &puke, GSM_TO_SM, LstarInfo->mInfo->c ); +//printf("LstarInfo->mInfo->Pm_North (SM Coords) = %g %g %g\n", puke.x, puke.y, puke.z ); +//Lgm_Convert_Coords( &LstarInfo->mInfo->Pm_South, &puke, GSM_TO_SM, LstarInfo->mInfo->c ); +//printf("LstarInfo->mInfo->Pm_South (SM Coords) = %g %g %g\n", puke.x, puke.y, puke.z ); +//Lgm_Convert_Coords( &LstarInfo->Spherical_Footprint_Pn[k], &puke, GSM_TO_SM, LstarInfo->mInfo->c ); +//printf("LstarInfo->Spherical_Footprint_Pn[k] (SM Coords) = %g %g %g\n", puke.x, puke.y, puke.z ); +if (LstarInfo->VerbosityLevel > 1) { + printf("\t\t%sTracing Full FL so that we can classify it. Starting at Spherical_Footprint_Pn[%d] = %g %g %g%s\n", PreStr, k, LstarInfo->Spherical_Footprint_Pn[k].x, LstarInfo->Spherical_Footprint_Pn[k].y, LstarInfo->Spherical_Footprint_Pn[k].z, PostStr ); +} +Lgm_TraceLine( &LstarInfo->Spherical_Footprint_Pn[k], &v2, LstarInfo->mInfo->Lgm_LossConeHeight, -1.0, 1e-8, FALSE, LstarInfo->mInfo ); +if (LstarInfo->VerbosityLevel > 1) { + printf("\t\t%sTraced Full FL so that we can classify it. Step size along FL: %g. Number of points: %d.%s\n", PreStr, LstarInfo->mInfo->Hmax, LstarInfo->mInfo->nPnts, PostStr ); +} +LstarInfo->Spherical_Footprint_Ps[k] = v2; +//Lgm_Convert_Coords( &LstarInfo->Spherical_Footprint_Ps[k], &puke, GSM_TO_SM, LstarInfo->mInfo->c ); +//printf("LstarInfo->Spherical_Footprint_Ps[k] (SM Coords) = %g %g %g\n", puke.x, puke.y, puke.z ); + + Type = ClassifyFL( k, LstarInfo ); + if (LstarInfo->VerbosityLevel > 1) { + printf("\t\t%sClassifying FL: Type = %d. %s\n", PreStr, Type, PostStr ); + } + +// CRAP +//for ( i=0; inMinima[i] > 2 ) LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_OPEN; + if ( (Type > 1) && (0==1) ){ if (LstarInfo->VerbosityLevel > 1) { - printf("\t\t%sTracing Full FL so that we can classify it. Starting at Spherical_Footprint_Pn[%d] = %g %g %g%s\n", PreStr, k, LstarInfo->Spherical_Footprint_Pn[k].x, LstarInfo->Spherical_Footprint_Pn[k].y, LstarInfo->Spherical_Footprint_Pn[k].z, PostStr ); + printf("\t\t\t%sShabansky orbit. Re-doing FL. Target I adjusted to: %g . (Original is: %g) %s\n", PreStr, I/2.0, I, PostStr ); } - Lgm_TraceLine( &LstarInfo->Spherical_Footprint_Pn[k], &v2, LstarInfo->mInfo->Lgm_LossConeHeight, -1.0, 1e-8, FALSE, LstarInfo->mInfo ); + + FoundShellLine = FindShellLine( I/2.0, &Ifound, LstarInfo->mInfo->Bm, MLT, &mlat, &r, mlat0, mlat_try, mlat1, &nIts, LstarInfo ); + + PredMinusActualMlat = pred_mlat - mlat; if (LstarInfo->VerbosityLevel > 1) { - printf("\t\t%sTraced Full FL so that we can classify it. Step size along FL: %g. Number of points: %d.%s\n", PreStr, LstarInfo->mInfo->Hmax, LstarInfo->mInfo->nPnts, PostStr ); + printf("\t\t%s________________________________________________________________________________________________________________________________%s\n\n", PreStr, PostStr ); + printf("\t\t%s >> Pred/Actual/Diff mlat: %g/%g/%g MLT/MLAT: %g %g I0: %g I: %g I-I0/2: %g (SHABANSKY)%s\n", PreStr, pred_mlat, mlat, PredMinusActualMlat, MLT, mlat, I, Ifound, Ifound-I/2.0, PostStr ); + printf("\t\t%s________________________________________________________________________________________________________________________________ %s\n\n\n", PreStr, PostStr ); } - LstarInfo->Spherical_Footprint_Ps[k] = v2; - - // Check for multiple minima and bounce regions -- but only if we have a valid FL with correct (I,Bm) - Type = ClassifyFL( k, LstarInfo ); - LstarInfo->nBounceRegions[k] = Type; + + } else { + + PredMinusActualMlat = pred_mlat - mlat; if (LstarInfo->VerbosityLevel > 1) { - printf("\t\t%sClassifying FL: Type = %d. %s\n", PreStr, Type, PostStr ); - } - - if ( (Type > 1) && (LstarInfo->ShabanskyHandling==LGM_SHABANSKY_HALVE_I) ){ - if (LstarInfo->VerbosityLevel > 0) { - printf("\t\t\t%sShabansky orbit. Re-doing FL. Target I adjusted to: %g . (Original is: %g) %s\n", PreStr, I/2.0, I, PostStr ); - } - - FoundShellLine = FindShellLine( I/2.0, &Ifound, LstarInfo->mInfo->Bm, MLT, &mlat, &r, mlat0, mlat_try, mlat1, &nIts, LstarInfo ); - //TODO: Do we need to test to make sure that the adjusted I is being found on a field line with multiple minima?? - PredMinusActualMlat = pred_mlat - mlat; - if (LstarInfo->VerbosityLevel > 1) { - printf("\t\t%s________________________________________________________________________________________________________________________________%s\n\n", PreStr, PostStr ); - printf("\t\t%s >> Pred/Actual/Diff mlat: %g/%g/%g MLT/MLAT: %g %g I0: %g I: %g I-I0/2: %g (SHABANSKY)%s\n", PreStr, pred_mlat, mlat, PredMinusActualMlat, MLT, mlat, I, Ifound, Ifound-I/2.0, PostStr ); - printf("\t\t%s________________________________________________________________________________________________________________________________ %s\n\n\n", PreStr, PostStr ); - } - - } else { - if (Type > 1) { - if ((LstarInfo->ShabanskyHandling==LGM_SHABANSKY_IGNORE) && (LstarInfo->VerbosityLevel > 0)) printf("Encountered multiple bounce regions: Ignoring. \n"); - if ((LstarInfo->ShabanskyHandling==LGM_SHABANSKY_REJECT) && (LstarInfo->VerbosityLevel > 0)) printf("Encountered multiple bounce regions: Should reject this and quit. Type = %d \n", Type); - } - PredMinusActualMlat = pred_mlat - mlat; - if (LstarInfo->VerbosityLevel > 1) { - printf("\t\t%s________________________________________________________________________________________________________________________________%s\n\n", PreStr, PostStr ); - printf("\t\t%s >> Pred/Actual/Diff mlat: %g/%g/%g MLT/MLAT: %g %g I0: %g I: %g I-I0: %g %s\n", PreStr, pred_mlat, mlat, PredMinusActualMlat, MLT, mlat, I, Ifound, Ifound-I, PostStr ); - printf("\t\t%s________________________________________________________________________________________________________________________________ %s\n\n\n", PreStr, PostStr ); - } + printf("\t\t%s________________________________________________________________________________________________________________________________%s\n\n", PreStr, PostStr ); + printf("\t\t%s >> Pred/Actual/Diff mlat: %g/%g/%g MLT/MLAT: %g %g I0: %g I: %g I-I0: %g %s\n", PreStr, pred_mlat, mlat, PredMinusActualMlat, MLT, mlat, I, Ifound, Ifound-I, PostStr ); + printf("\t\t%s________________________________________________________________________________________________________________________________ %s\n\n\n", PreStr, PostStr ); } + + } + + + + + + + + + + + + + + + + + if ( FoundShellLine > 0 ) { + done2 = TRUE; } else if ( Count > 2 ) { - // Tried to find valid FL more than three times done2 = TRUE; - if (LstarInfo->VerbosityLevel >0) { printf(" \t%sNo valid I - Drift Shell not closed: L* = undefined (FoundShellLine = %d)%s\n", PreStr, FoundShellLine, PostStr); fflush(stdout); } + if (LstarInfo->VerbosityLevel >1) { printf(" \t%sNo valid I - Drift Shell not closed: L* = undefined (FoundShellLine = %d)%s\n", PreStr, FoundShellLine, PostStr); fflush(stdout); } FoundShellLine = 0; - break;//return(-3); + return(-3); } else { ++Count; } - } //end of while loop - - /* - * Test for open drift path and exit gracefully if required - */ - if ( (k > 0) && (FoundShellLine <= 0) ) { - // After initial FL, failed to find matching I,Bm - doExit = TRUE; - } else if ( (k > 0) && (Type > 1) && (LstarInfo->ShabanskyHandling==LGM_SHABANSKY_REJECT) ) { - // After initial FL, found I,Bm in bifurcated drift orbit. Desired behavior is bailing out. - doExit = TRUE; - } - if (doExit) { - for ( i=0; inPnts; ++i ) { - if ( LstarInfo->nMinima[i] > 1 ) { - if ( LstarInfo->nBounceRegions[i] > 1 ) { - nShabII++; - } else { - nShabI++; - } - } - } - - if (nShabII > 0) { - LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_OPEN_SHABANSKY_II; - } else if (nShabI > 0) { - LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_OPEN_SHABANSKY_I; - } else { - LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_OPEN; - } - - // All open drift shell types should bail out here. - if (LstarInfo->VerbosityLevel > 0) { - printf("\n\t\t%sL*, Dipole Approximation.\n%s", PreStr, PostStr ); - printf("\t\t%s Magnetic Flux: %.15lf%s\n", PreStr, Phi1, PostStr ); - printf("\t\t%s L*: %.15lf%s\n", PreStr, LstarInfo->LS_dip_approx, PostStr ); - printf("\t\t%s L* (Using McIlwain M): %.15lf%s\n", PreStr, -2.0*M_PI*LstarInfo->mInfo->c->M_cd_McIlwain /Phi1, PostStr ); - printf("\n\t\t%sL*, Full Field.%s\n", PreStr, PostStr ); - printf("\t\t%s Magnetic Flux: %.15lf%s\n", PreStr, Phi2, PostStr ); - printf("\t\t%s L*: %.15lf%s\n", PreStr, LstarInfo->LS, PostStr ); - printf("\t\t%s L* (Using McIlwain M): %.15lf%s\n", PreStr, -2.0*M_PI*LstarInfo->mInfo->c->M_cd_McIlwain /Phi2, PostStr ); - if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_OPEN ) printf("\n\t\t%sDrift Orbit Type: OPEN%s\n", PreStr, PostStr ); - else if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_OPEN_SHABANSKY_I) printf("\n\t\t%sDrift Orbit Type: OPEN_SHABANSKY_I%s\n", PreStr, PostStr ); - else if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_OPEN_SHABANSKY_II) printf("\n\t\t%sDrift Orbit Type: OPEN_SHABANSKY_II%s\n", PreStr, PostStr ); - printf("\n\n\n" ); - } - return(-4); //TODO: set return code based on failure mode - } + } if (LstarInfo->VerbosityLevel > 2) { printf("\t\t%sActual mlat = %g MLT = %g r = %g Ifound = %g\t Count = %d%s", PreStr, mlat, MLT, r, Ifound, Count, PostStr ); fflush(stdout); } @@ -1135,6 +1138,9 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ * equator, we may have initially confused the north and south mirror * points. We end up sorting the confusion out, but we really need to make * sure that as we proceed, we refer to the correct values. + * + * + * */ // u = LstarInfo->mInfo->Pm_North; // Lgm_Convert_Coords( &u, &v, GSM_TO_SM, LstarInfo->mInfo->c ); @@ -1153,6 +1159,7 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ MirrorMLT[k] = MLT; MirrorMlat[k] = mlat; + /* * convert mirror point to GSM. */ @@ -1185,9 +1192,8 @@ int Lstar( Lgm_Vector *vin, Lgm_LstarInfo *LstarInfo ){ * elipsoid. */ LstarInfo->mInfo->Hmax = 0.1; - if ( !Lgm_TraceToSphericalEarth( &v, &w, LstarInfo->mInfo->Lgm_LossConeHeight, 1.0, 1e-7, LstarInfo->mInfo ) ){ - break;//return(-4); - } +// if ( !Lgm_TraceToSphericalEarth( &v, &w, LstarInfo->mInfo->Lgm_LossConeHeight, 1.0, 1e-7, LstarInfo->mInfo ) ){ return(-4); } + if ( !Lgm_TraceToSphericalEarth( &v, &w, LstarInfo->mInfo->Lgm_LossConeHeight, 1.0, 1e-11, LstarInfo->mInfo ) ){ return(-4); } LstarInfo->Spherical_Footprint_Pn[k] = w; /* @@ -1218,7 +1224,7 @@ LstarInfo->FindShellPmin = TRUE; * Compute the gradient of I, Sb and Vgc */ if ( LstarInfo->ComputeVgc ) { - // Lgm_Grad_I() and other routines may modify mInfo in undesirable ways, so give it a copy. + // Lgm_Grad_I() and other rotuines may modify mInfo in undesirable ways, so give it a copy. mInfo2 = Lgm_CopyMagInfo( LstarInfo->mInfo ); mInfo2->FirstCall = TRUE; @@ -1226,7 +1232,7 @@ LstarInfo->FindShellPmin = TRUE; mInfo2->Lgm_Sb_Integrator_epsabs = 0.0; mInfo2->Lgm_Sb_Integrator_epsrel = 1e-3; double Sb = SbIntegral( mInfo2 ); -Sb = 1.0; //TODO: why is this hardcoded? +Sb = 1.0; Lgm_Grad_I( &LstarInfo->Pmin[k], &LstarInfo->GradI[k], mInfo2 ); @@ -1239,22 +1245,22 @@ Sb = 1.0; //TODO: why is this hardcoded? Lgm_FreeMagInfo( mInfo2 ); double K = LstarInfo->KineticEnergy; // keV -K = 1000.0; //keV //TODO: why is this hardcoded? +K = 1000.0; //keV K *= 1e3*LGM_e; // Joules double M = LstarInfo->Mass; // kg -M = ELECTRON_MASS; // kg //TODO: why is this hardcoded? +M = ELECTRON_MASS; // kg /* * Note: Kinetic energy is difference between total E and rest Energy - * In non-rel. limit, the factor g=2. So ratio of Non Rel to Rel velocity is + * In non-rel. limit, the factor g=2. So ration of Non Rel to Rel velocity is * (2Eta+2)/(Eta+2) */ double Eta = K/(M*CC*CC); double g = K*(2.0+Eta)/(1.0+Eta); - double q = 1.0; // units of elementary charge + double q = 1.0; // units of elementary charge q *= 1.6021e-19; // Coulombs Sb *= 6371e3; // m double f = g/(q*Sb*B)/1000.0; @@ -1272,7 +1278,6 @@ M = ELECTRON_MASS; // kg //TODO: why is this hardcoded? Lgm_TraceLine( &LstarInfo->Spherical_Footprint_Pn[k], &v2, LstarInfo->mInfo->Lgm_LossConeHeight, -1.0, 1e-8, FALSE, LstarInfo->mInfo ); LstarInfo->Spherical_Footprint_Ps[k] = v2; - //FILE *fppp; //double AlphaEq; //fppp = fopen("FL.txt","a"); @@ -1283,6 +1288,8 @@ M = ELECTRON_MASS; // kg //TODO: why is this hardcoded? //} //fclose(fppp); +//Type = ClassifyFL( k, LstarInfo ); +//printf("k, Type = %d %d\n", k, Type); LstarInfo->nMinMax = k; nnn = LstarInfo->mInfo->nPnts; smax = LstarInfo->mInfo->s[nnn-1]; @@ -1298,9 +1305,12 @@ M = ELECTRON_MASS; // kg //TODO: why is this hardcoded? } LstarInfo->nFieldPnts[k] = tkk; + + LstarInfo->Spherical_Footprint_Ss[k] = LstarInfo->s_gsm[k][0]; LstarInfo->Spherical_Footprint_Sn[k] = smax; + /* * Find true footpoints (i.e. relative to ellipsoid), we may want to do an additional trace here... */ @@ -1336,11 +1346,18 @@ M = ELECTRON_MASS; // kg //TODO: why is this hardcoded? LstarInfo->Mirror_Sn[k] += LstarInfo->mInfo->Trace_s; } + + + + } + + ++k; - LstarInfo->nPnts = k; - } // end MLT for loop, if we get this far we've found a FL with the right I,Bm at each requested MLT + + } // end MLT for loop + LstarInfo->nPnts = k; /* @@ -1399,53 +1416,50 @@ FIX */ // gsl_set_error_handler_off(); // Turn off gsl default error handler LstarInfo->acc = gsl_interp_accel_alloc( ); +// LstarInfo->pspline = gsl_interp_alloc( gsl_interp_cspline_periodic, LstarInfo->nSplnPnts ); LstarInfo->pspline = gsl_interp_alloc( gsl_interp_cspline_periodic, LstarInfo->nSplnPnts ); +// LstarInfo->pspline = gsl_interp_alloc( gsl_interp_linear, LstarInfo->nSplnPnts ); + //printf ("spline uses '%s' interpolation.\n", gsl_interp_name( LstarInfo->pspline )); gsl_interp_init( LstarInfo->pspline, LstarInfo->xa, LstarInfo->ya, LstarInfo->nSplnPnts ); +//for(i=0; im; i++){ +//printf("HERE 2: LstarInfo->xa[%d] = %g LstarInfo->ya[%d] = %g \n", i, LstarInfo->xa[i], i, LstarInfo->ya[i] ); +//} - /* - * Now calculate Lstar - */ Phi1 = MagFlux( LstarInfo ); - LstarInfo->LS_dip_approx = -2.0*M_PI*LstarInfo->Mused/Phi1; + LstarInfo->LS_dip_approx = -2.0*M_PI*LstarInfo->mInfo->c->M_cd_2010 /Phi1; Phi2 = MagFlux2( LstarInfo ); - LstarInfo->LS = -2.0*M_PI*LstarInfo->Mused /Phi2; - LstarInfo->LS_McIlwain_M = -2.0*M_PI*LstarInfo->mInfo->c->M_cd_McIlwain /Phi2; + LstarInfo->LS = -2.0*M_PI*LstarInfo->mInfo->c->M_cd_2010 /Phi2; + LstarInfo->LS_McIlwain_M = -2.0*M_PI*LstarInfo->mInfo->c->M_cd_McIllwain /Phi2; + + /* - * Determine the type of the orbit. If we got here our drift orbit should be closed... + * Determine the type of the orbit. We will not be here if we bailed early.. So LGM_DRIFT_ORBIT_OPEN_SHABANSKY + * cant be determined here ... */ LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_CLOSED; - for ( i=0; inPnts; ++i ) { - //nMinima just counts minima. number of bounce regions is tracked separately (as return type of ClassifyFL) - if ( LstarInfo->nMinima[i] > 1 ) { - if ( LstarInfo->nBounceRegions[i] > 1 ) { - nShabII++; - } else { - nShabI++; - } - } - } - if (nShabII > 0) { - LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_CLOSED_SHABANSKY_II; - } else if (nShabI > 0) { - LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_CLOSED_SHABANSKY_I; - } + for ( i=0; inPnts; ++i ) if ( LstarInfo->nMinima[i] > 1 ) LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_CLOSED_SHABANSKY; + if ( LstarInfo->LS < 0.0 ) LstarInfo->DriftOrbitType = LGM_DRIFT_ORBIT_OPEN; + - if (LstarInfo->VerbosityLevel > 0) { + + + + if (LstarInfo->VerbosityLevel > 1) { printf("\n\t\t%sL*, Dipole Approximation.\n%s", PreStr, PostStr ); printf("\t\t%s Magnetic Flux: %.15lf%s\n", PreStr, Phi1, PostStr ); printf("\t\t%s L*: %.15lf%s\n", PreStr, LstarInfo->LS_dip_approx, PostStr ); - printf("\t\t%s L* (Using McIlwain M): %.15lf%s\n", PreStr, -2.0*M_PI*LstarInfo->mInfo->c->M_cd_McIlwain /Phi1, PostStr ); + printf("\t\t%s L* (Using McIllwain M): %.15lf%s\n", PreStr, -2.0*M_PI*LstarInfo->mInfo->c->M_cd_McIllwain /Phi1, PostStr ); printf("\n\t\t%sL*, Full Field.%s\n", PreStr, PostStr ); printf("\t\t%s Magnetic Flux: %.15lf%s\n", PreStr, Phi2, PostStr ); printf("\t\t%s L*: %.15lf%s\n", PreStr, LstarInfo->LS, PostStr ); - printf("\t\t%s L* (Using McIlwain M): %.15lf%s\n", PreStr, -2.0*M_PI*LstarInfo->mInfo->c->M_cd_McIlwain /Phi2, PostStr ); - if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_CLOSED ) printf("\n\t\t%sDrift Orbit Type: CLOSED%s\n", PreStr, PostStr ); - else if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_CLOSED_SHABANSKY_I) printf("\n\t\t%sDrift Orbit Type: SHABANSKY_I%s\n", PreStr, PostStr ); - else if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_CLOSED_SHABANSKY_II) printf("\n\t\t%sDrift Orbit Type: SHABANSKY_II%s\n", PreStr, PostStr ); + printf("\t\t%s L* (Using McIllwain M): %.15lf%s\n", PreStr, -2.0*M_PI*LstarInfo->mInfo->c->M_cd_McIllwain /Phi2, PostStr ); + if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_CLOSED ) printf("\n\t\t%sDrift Orbit Type: CLOSED%s\n", PreStr, PostStr ); + else if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_CLOSED_SHABANSKY) printf("\n\t\t%sDrift Orbit Type: SHABANSKY%s\n", PreStr, PostStr ); + else if ( LstarInfo->DriftOrbitType == LGM_DRIFT_ORBIT_OPEN ) printf("\n\t\t%sDrift Orbit Type: OPEN%s\n", PreStr, PostStr ); printf("\n\n\n" ); } @@ -1536,7 +1550,7 @@ double MagFlux( Lgm_LstarInfo *LstarInfo ) { r = 1.0 + LstarInfo->mInfo->Lgm_LossConeHeight/WGS84_A; - return( -result*LstarInfo->Mused/r ); + return( -result*LstarInfo->mInfo->c->M_cd_2010/r ); } @@ -1544,6 +1558,13 @@ double MagFlux( Lgm_LstarInfo *LstarInfo ) { + + + + + + + /* * Lets integrate the real field. I.e. dont assume a dipole field */ @@ -1959,12 +1980,10 @@ int Lgm_LCDS( long int Date, double UTC, double brac1, double brac2, double Kin, } else { return(-8); } - if (LstarInfo->VerbosityLevel > 0) { - printf("[Inner bracket] Alpha (of K) is %g (%g)\n", Alpha, Kin); - sa = sin( LstarInfo_brac1->PitchAngle*RadPerDeg ); sa2 = sa*sa; - LstarInfo_brac1->mInfo->Bm = LstarInfo_brac1->mInfo->Bmin/sa2; - printf("[Inner bracket] Bm, Bmin = is %g, %g\n", LstarInfo_brac1->mInfo->Bm, LstarInfo_brac1->mInfo->Bmin); - } + if (LstarInfo->VerbosityLevel > 0) printf("[Inner bracket] Alpha (of K) is %g (%g)\n", Alpha, Kin); + sa = sin( LstarInfo_brac1->PitchAngle*RadPerDeg ); sa2 = sa*sa; + LstarInfo_brac1->mInfo->Bm = LstarInfo_brac1->mInfo->Bmin/sa2; + if (LstarInfo->VerbosityLevel > 0) printf("[Inner bracket] Bm, Bmin = is %g, %g\n", LstarInfo_brac1->mInfo->Bm, LstarInfo_brac1->mInfo->Bmin); //Only continue if bracket 1 is closed FL //Get L* LS_Flag = Lstar( &v3, LstarInfo_brac1); @@ -2008,13 +2027,10 @@ int Lgm_LCDS( long int Date, double UTC, double brac1, double brac2, double Kin, else { Alpha = LGM_FILL_VALUE; } - if (LstarInfo->VerbosityLevel > 0) { - printf("[Outer bracket] Alpha (of K) is %g (%g)\n", Alpha, Kin); - sa = sin( LstarInfo_brac2->PitchAngle*RadPerDeg ); sa2 = sa*sa; - LstarInfo_brac2->mInfo->Bm = LstarInfo_brac2->mInfo->Bmin/sa2; - printf("[Outer bracket] Bm, Bmin = is %g, %g\n", LstarInfo_brac2->mInfo->Bm, LstarInfo_brac2->mInfo->Bmin); - } LstarInfo_brac2->PitchAngle = Alpha; + sa = sin( LstarInfo_brac2->PitchAngle*RadPerDeg ); sa2 = sa*sa; + + LstarInfo_brac2->mInfo->Bm = LstarInfo_brac2->mInfo->Bmin/sa2; LS_Flag = Lstar( &v3, LstarInfo_brac2); if (LstarInfo_brac2->LS != LGM_FILL_VALUE) { //move outer bracket out and try again @@ -2031,7 +2047,9 @@ int Lgm_LCDS( long int Date, double UTC, double brac1, double brac2, double Kin, Alpha = LGM_FILL_VALUE; } LstarInfo_brac2->PitchAngle = Alpha; + sa = sin( LstarInfo_brac2->PitchAngle*RadPerDeg ); sa2 = sa*sa; if ( Lgm_Trace( &Pouter, &v1, &v2, &v3, 120.0, 0.01, TRACE_TOL, LstarInfo_brac2->mInfo ) == LGM_CLOSED ) { + LstarInfo_brac2->mInfo->Bm = LstarInfo_brac2->mInfo->Bmin/sa2; LS_Flag = Lstar( &v3, LstarInfo_brac2); if (LstarInfo_brac2->LS != LGM_FILL_VALUE) { FreeLstarInfo( LstarInfo_brac1 ); @@ -2072,9 +2090,11 @@ int Lgm_LCDS( long int Date, double UTC, double brac1, double brac2, double Kin, Alpha = LGM_FILL_VALUE; } LstarInfo_test->PitchAngle = Alpha; + sa = sin( LstarInfo_test->PitchAngle*RadPerDeg ); sa2 = sa*sa; //If test point is closed FL then check for undefined L*. //Get L* + LstarInfo_test->mInfo->Bm = LstarInfo_test->mInfo->Bmin/sa2; LS_Flag = Lstar( &v3, LstarInfo_test); if ( (LS_Flag > 0) || (LstarInfo_test->LS != LGM_FILL_VALUE) ){ //Drift shell defined diff --git a/libLanlGeoMag/DriftShell.c b/libLanlGeoMag/DriftShell.c index bd9554285..6ecb6606b 100644 --- a/libLanlGeoMag/DriftShell.c +++ b/libLanlGeoMag/DriftShell.c @@ -938,7 +938,7 @@ int FindBmRadius( double Bm, double MLT, double mlat, double *r, double tol, Lgm bfi.func = &RadBmFunc; bfi.Val = Bm; Flag = Lgm_Brent( MinBracket[i].a, MinBracket[i].b, MinBracket[i].c, &bfi, tol, r, &D ); - if (LstarInfo->VerbosityLevel > 1) { printf( "%sFindBmRadius: Minima found at r = %g D = %g %s\n", LstarInfo->PreStr, *r, D, LstarInfo->PostStr ); } + if (LstarInfo->VerbosityLevel > 0) { printf( "%sFindBmRadius: Minima found at r = %g D = %g %s\n", LstarInfo->PreStr, *r, D, LstarInfo->PostStr ); } if ( Flag ) { if ( fabs(D) < tol ) { // value found. diff --git a/libLanlGeoMag/Lgm/Lgm_CTrans.h b/libLanlGeoMag/Lgm/Lgm_CTrans.h index a07132061..30e07d5db 100644 --- a/libLanlGeoMag/Lgm/Lgm_CTrans.h +++ b/libLanlGeoMag/Lgm/Lgm_CTrans.h @@ -707,8 +707,8 @@ typedef struct Lgm_CTrans { * the IGRF field. Note that these are the basis for defining * Mag coord systems. That's why they are here and not somewhere else... */ - double M_cd; /**< centered dipole Magnetic moment of epoch. (nT Re^3)*/ - double M_cd_McIlwain; /**< magnetic dipole moment used by McIlwain to compute L. Sometimes want to use this for consistency? */ + double M_cd; /**< centered dipole Magnetic moment. (nT Re^3)*/ + double M_cd_McIllwain; /**< magnetic dipole moment used by McIllwain to compute L. Sometimes want to use this for consistency? */ double M_cd_2010; /**< magnetic dipole moment for epoch 2010-01-01T00:00:00Z. Used by us to compute L*. */ double CD_gcolat; /**< Geographic colat of centered dipole axis (deg.) */ double CD_glon; /**< Geographic long. of centered dipole axis (deg.) */ diff --git a/libLanlGeoMag/Lgm/Lgm_HDF5.h b/libLanlGeoMag/Lgm/Lgm_HDF5.h index ccba740f7..cca8956ac 100644 --- a/libLanlGeoMag/Lgm/Lgm_HDF5.h +++ b/libLanlGeoMag/Lgm/Lgm_HDF5.h @@ -9,7 +9,7 @@ #include #include #include "Lgm/Lgm_DynamicMemory.h" -#define H5_NO_DEPRECATED_SYMBOLS +/* #define H5_NO_DEPRECATED_SYMBOLS */ #include diff --git a/libLanlGeoMag/Lgm/Lgm_LstarInfo.h b/libLanlGeoMag/Lgm/Lgm_LstarInfo.h index d33b7264a..91676a7b8 100644 --- a/libLanlGeoMag/Lgm/Lgm_LstarInfo.h +++ b/libLanlGeoMag/Lgm/Lgm_LstarInfo.h @@ -14,24 +14,11 @@ #define RE (6378.135e3) /* Earth Radius, m */ #define CC (2.99792458e8) /* Speed of Light, m/s */ -#define LGM_DRIFT_ORBIT_CLOSED 1 -#define LGM_DRIFT_ORBIT_CLOSED_SHABANSKY 2 -#define LGM_DRIFT_ORBIT_CLOSED_SHABANSKY_I 21 -#define LGM_DRIFT_ORBIT_CLOSED_SHABANSKY_II 22 -#define LGM_DRIFT_ORBIT_CLOSED_SHABANSKY_III 23 -#define LGM_DRIFT_ORBIT_OPEN 3 -#define LGM_DRIFT_ORBIT_OPEN_SHABANSKY 4 -#define LGM_DRIFT_ORBIT_OPEN_SHABANSKY_I 41 -#define LGM_DRIFT_ORBIT_OPEN_SHABANSKY_II 42 -#define LGM_DRIFT_ORBIT_OPEN_SHABANSKY_III 43 - -#define LGM_SHABANSKY_IGNORE 0 -#define LGM_SHABANSKY_HALVE_I 1 -#define LGM_SHABANSKY_REJECT 2 - -#define LGM_LSTAR_MOMENT_CDIP 0 -#define LGM_LSTAR_MOMENT_CDIP_2010 1 -#define LGM_LSTAR_MOMENT_MCILWAIN 2 +#define LGM_DRIFT_ORBIT_CLOSED 1 +#define LGM_DRIFT_ORBIT_CLOSED_SHABANSKY 2 +#define LGM_DRIFT_ORBIT_OPEN 3 +#define LGM_DRIFT_ORBIT_OPEN_SHABANSKY 4 + #define LGM_LSTARINFO_MAX_FL 300 #define LGM_LSTARINFO_MAX_MINIMA 300 @@ -41,8 +28,6 @@ typedef struct Lgm_LstarInfo { int nFLsInDriftShell; //!< Number of Field Lines to use when constructing Drift Shell. int LstarQuality; //!< Quality factor to use [0,8] -- higher gives more precise results. - int ShabanskyHandling; //!< Set how Lstar calculations are to handle Shabansky orbits - int LstarMoment; //!< Select dipole magnetic moment to use in conversion of Phi to Lstar double KineticEnergy; //!< Particle kinetic energy (only for energy dep. quantities.) double Mass; //!< Particle mass @@ -115,14 +100,12 @@ typedef struct Lgm_LstarInfo { int DriftOrbitType; // e.g. Open, Closed, Shabansky int nMinMax; // Number of valid FLs represented in nMinima[] and nMaxima[] (we may have bailed early) int nMinima[ LGM_LSTARINFO_MAX_MINIMA ]; // # of minima on FL - int nMaxima[ LGM_LSTARINFO_MAX_MINIMA ]; // # of maxima on FL (not including endpoints) - int nBounceRegions[ LGM_LSTARINFO_MAX_MINIMA ]; // # of bounce regions on FL (as particle may not be confined in a minimum) + int nMaxima[ LGM_LSTARINFO_MAX_MINIMA ]; // # of maxima on FL (not including endpoints int nSplnPnts; double xa [ 3*LGM_LSTARINFO_MAX_FL ], ya[ 3*LGM_LSTARINFO_MAX_FL ], y2[ 3*LGM_LSTARINFO_MAX_FL ]; - double Phi; - double Mused; // Magnetic moment to use in Lstar + double Phi; gsl_interp_accel *acc; gsl_interp *pspline; diff --git a/libLanlGeoMag/Lgm/Lgm_MagModelInfo.h b/libLanlGeoMag/Lgm/Lgm_MagModelInfo.h index 01f0f705f..6a5fc3096 100644 --- a/libLanlGeoMag/Lgm/Lgm_MagModelInfo.h +++ b/libLanlGeoMag/Lgm/Lgm_MagModelInfo.h @@ -73,11 +73,10 @@ #define QUADRATIC_DFI 3 #define NEWTON_INTERP 4 -#define LGM_CDIP 0 -#define LGM_EDIP 1 -#define LGM_IGRF 2 -#define LGM_DUNGEY 3 -#define LGM_JENSENCAIN1960 4 +#define LGM_CDIP 0 +#define LGM_EDIP 1 +#define LGM_IGRF 2 +#define LGM_DUNGEY 3 #define LGM_MAX_INTERP_PNTS 10000 diff --git a/libLanlGeoMag/Lgm/Lgm_NrlMsise00.h b/libLanlGeoMag/Lgm/Lgm_NrlMsise00.h index 33bafd833..b3578e36f 100644 --- a/libLanlGeoMag/Lgm/Lgm_NrlMsise00.h +++ b/libLanlGeoMag/Lgm/Lgm_NrlMsise00.h @@ -33,7 +33,7 @@ typedef struct Lgm_Msis00Info { double TN1[6], TN2[5], TN3[6], TGN1[3], TGN2[3], TGN3[3]; // PARMB COMMON BLOCK VARS - double GSURF, Rref; + double GSURF, RE; // CSW COMMON BLOCK VARS double *SW, ISW, *SWC; diff --git a/libLanlGeoMag/Lgm/Lgm_QinDenton.h b/libLanlGeoMag/Lgm/Lgm_QinDenton.h index fadb3d2ce..4c8b4cb33 100644 --- a/libLanlGeoMag/Lgm/Lgm_QinDenton.h +++ b/libLanlGeoMag/Lgm/Lgm_QinDenton.h @@ -62,7 +62,7 @@ void Lgm_init_QinDentonDefaults( Lgm_QinDenton *q, int Verbose ); void Lgm_destroy_QinDenton( Lgm_QinDenton *q ); void Lgm_destroy_QinDenton_children( Lgm_QinDenton *q ); void Lgm_read_QinDenton( long int Date, Lgm_QinDenton *q ); -int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Persistence ); +void Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Persistence ); void Lgm_set_QinDenton( Lgm_QinDentonOne *p, Lgm_MagModelInfo *m ); diff --git a/libLanlGeoMag/Lgm_CTrans.c b/libLanlGeoMag/Lgm_CTrans.c index 7a0458d4e..cd4fa74b5 100644 --- a/libLanlGeoMag/Lgm_CTrans.c +++ b/libLanlGeoMag/Lgm_CTrans.c @@ -944,7 +944,7 @@ void Lgm_Set_Coord_Transforms( long int date, double UTC, Lgm_CTrans *c ) { printf("\n"); printf("IGRF-derived quantities:\n"); printf(" M_cd = %.10lf nT\n", c->M_cd); - printf(" M_cd_McIlwain = %.10lf nT\n", c->M_cd_McIlwain); + printf(" M_cd_McIllwain = %.10lf nT\n", c->M_cd_McIllwain); printf(" M_cd_2010 = %.10lf nT\n", c->M_cd_2010); printf(" CD_gcolat = %lf (deg.) ( ", c->CD_gcolat); Lgm_Print_DMSd( c->CD_gcolat ); printf(" )\n"); printf(" CD_glon = %lf (deg.) ( ", c->CD_glon); Lgm_Print_DMSd( c->CD_glon ); printf(" )\n"); diff --git a/libLanlGeoMag/Lgm_ComputeLstarVersusPA.c b/libLanlGeoMag/Lgm_ComputeLstarVersusPA.c index 9e321f0e8..76bfa6436 100644 --- a/libLanlGeoMag/Lgm_ComputeLstarVersusPA.c +++ b/libLanlGeoMag/Lgm_ComputeLstarVersusPA.c @@ -53,6 +53,11 @@ void Lgm_ComputeLstarVersusPA( long int Date, double UTC, Lgm_Vector *u, int nAl int i, k, LS_Flag, nn, tk, TraceFlag; char *PreStr, *PostStr; + /* These should be set by the user in the setup up MagEphemInfo no in here */ + //MagEphemInfo->LstarInfo->SaveShellLines = FALSE; + //MagEphemInfo->LstarInfo->FindShellPmin = FALSE; + //MagEphemInfo->LstarInfo->ComputeVgc = FALSE; + //MagEphemInfo->LstarInfo->ComputeVgc = FALSE; LstarInfo = MagEphemInfo->LstarInfo; // Save Date, UTC to MagEphemInfo structure @@ -82,10 +87,12 @@ void Lgm_ComputeLstarVersusPA( long int Date, double UTC, Lgm_Vector *u, int nAl for ( i=0; inAlpha; i++ ){ sa = sin( MagEphemInfo->Alpha[i]*RadPerDeg ); sa2 = sa*sa; MagEphemInfo->Bm[i] = Blocal/sa2; +//printf("Bm[%d] = %g\n", i, MagEphemInfo->Bm[i] ); } + /* * Compute Field-related quantities for each Pitch Angle. * @@ -105,7 +112,7 @@ void Lgm_ComputeLstarVersusPA( long int Date, double UTC, Lgm_Vector *u, int nAl MagEphemInfo->Smin = LstarInfo->mInfo->Smin; MagEphemInfo->Bmin = LstarInfo->mInfo->Bmin; //printf("P = %g %g %g Blocal = %lf Bmin = %lf \n", u->x, u->y, u->z, Blocal, MagEphemInfo->Bmin ); - //MagEphemInfo->Mref = LstarInfo->mInfo->c->M_cd_McIlwain; + //MagEphemInfo->Mref = LstarInfo->mInfo->c->M_cd_McIllwain; MagEphemInfo->Mref = LstarInfo->mInfo->c->M_cd_2010; MagEphemInfo->Mcurr = LstarInfo->mInfo->c->M_cd; MagEphemInfo->Mused = MagEphemInfo->Mref; @@ -190,7 +197,10 @@ void Lgm_ComputeLstarVersusPA( long int Date, double UTC, Lgm_Vector *u, int nAl //////////////////////////////NOTE //////////////////////////////NOTE We are giving Lstar the Min B point ALREADY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //////////////////////////////NOTE +//////////////////////////////NOTE +//////////////////////////////NOTE +//printf("LstarInfo2->mInfo->Bm = %g\n", LstarInfo2->mInfo->Bm); LS_Flag = Lstar( &v3, LstarInfo2); if (LstarInfo3->VerbosityLevel >= 2 ) { diff --git a/libLanlGeoMag/Lgm_IGRF.c b/libLanlGeoMag/Lgm_IGRF.c index 49b7b55b6..945d95a43 100644 --- a/libLanlGeoMag/Lgm_IGRF.c +++ b/libLanlGeoMag/Lgm_IGRF.c @@ -1094,8 +1094,8 @@ void Lgm_InitIGRF( double g[14][14], double h[14][14], int N, int Flag, Lgm_CTra * Compute dipole moments. */ c->M_cd = H0; - c->M_cd_McIlwain = 31165.3; - c->M_cd_2010 = 29950.1686985232; + c->M_cd_McIllwain = 31165.3; + c->M_cd_2010 = 29950.1686985232; c->CD_gcolat = M_PI - acos(g[1][0]/H0); c->CD_glon = atan(h[1][1]/g[1][1]); diff --git a/libLanlGeoMag/Lgm_InitMagEphemInfo.c b/libLanlGeoMag/Lgm_InitMagEphemInfo.c index a9074615e..9c3fb0901 100644 --- a/libLanlGeoMag/Lgm_InitMagEphemInfo.c +++ b/libLanlGeoMag/Lgm_InitMagEphemInfo.c @@ -23,10 +23,10 @@ void Lgm_SetMagEphemLstarQuality( int Quality, int nFLsInDriftShell, Lgm_MagEphe MagEphemInfo->LstarQuality = 3; } - if ( (nFLsInDriftShell >= 6) && (nFLsInDriftShell <= 240) ){ + if ( (nFLsInDriftShell >= 6) && (Quality <= 240) ){ MagEphemInfo->nFLsInDriftShell = nFLsInDriftShell; } else { - printf( "Lgm_MagEphemSetLstarQuality: nFLsInDriftShell not in range [6,240] (Got %d). Setting to 24).\n", nFLsInDriftShell ); + printf( "Lgm_MagEphemSetLstarQuality: nFLsInDriftShell not in range [0,240] (Got %d). Setting to 24).\n", nFLsInDriftShell ); MagEphemInfo->nFLsInDriftShell = 24; } diff --git a/libLanlGeoMag/Lgm_InitMagInfo.c b/libLanlGeoMag/Lgm_InitMagInfo.c index 885619ee2..03d945305 100644 --- a/libLanlGeoMag/Lgm_InitMagInfo.c +++ b/libLanlGeoMag/Lgm_InitMagInfo.c @@ -339,13 +339,6 @@ void Lgm_MagModelInfo_Set_MagModel( int InternalModel, int ExternalModel, Lgm_Ma strcpy( m->IntMagModelStr4, "Comments: Centered dipole + a uniform -Bz component. Not very realistic, but L* can be computed analytically, so it makes a good test for L* numerics." ); break; - case LGM_JENSENCAIN1960: - strcpy( m->IntMagModelStr1, "DUNGEY" ); - strcpy( m->IntMagModelStr2, "Dungey Field Model" ); - strcpy( m->IntMagModelStr3, "Reference: See Jensen DC, and Cain, JC (1962), An interim geomagnetic field, J. Geophys. Res., 67, 3568–3569" ); - strcpy( m->IntMagModelStr4, "Comments: Low-order approximation to IGRF valid for 1960. Used to bin some trapped particle measurements after Starfish." ); - break; - case LGM_IGRF: default: strcpy( m->IntMagModelStr1, "IGRF12" ); @@ -375,8 +368,6 @@ void Lgm_MagModelInfo_Set_MagModel( int InternalModel, int ExternalModel, Lgm_Ma m->Bfield = Lgm_B_edip; } else if ( InternalModel == LGM_DUNGEY ) { m->Bfield = Lgm_B_Dungey; - } else if ( InternalModel == LGM_JENSENCAIN1960 ) { - m->Bfield = Lgm_B_JensenCain1960; } else { m->Bfield = Lgm_B_igrf; } diff --git a/libLanlGeoMag/Lgm_McIlwain_L.c b/libLanlGeoMag/Lgm_McIlwain_L.c index 869db732d..cf65a954f 100644 --- a/libLanlGeoMag/Lgm_McIlwain_L.c +++ b/libLanlGeoMag/Lgm_McIlwain_L.c @@ -47,8 +47,6 @@ double Lgm_McIlwain_L( long int Date, double UTC, Lgm_Vector *u, double Alpha, i Lgm_Vector v1, v2, v3, Bvec, Bvectmp, Ptmp, u_scale; double rat, B, sa, sa2, Blocal, dSa, dSb, r, SS, L, stmp, Hdid, Hnext, Btmp; - if (mInfo->VerbosityLevel > 0) printf("Lgm_McIlwain_L: VerbosityLevel = %d\n", mInfo->VerbosityLevel); - u_scale.x = u_scale.y = u_scale.z = 1.0; *I = LGM_FILL_VALUE; diff --git a/libLanlGeoMag/Lgm_NrlMsise00.c b/libLanlGeoMag/Lgm_NrlMsise00.c index 31f0c7302..231ba52ad 100644 --- a/libLanlGeoMag/Lgm_NrlMsise00.c +++ b/libLanlGeoMag/Lgm_NrlMsise00.c @@ -2,7 +2,7 @@ static const double RGAS = 831.4; -#define ZETA(ZZ,ZL,p) ( (ZZ-ZL)*(p->Rref+ZL)/(p->Rref+ZZ) ) +#define ZETA(ZZ,ZL,p) ( (ZZ-ZL)*(p->RE+ZL)/(p->RE+ZZ) ) /*---------------------------------------------------------------------- * SUBROUTINE GTD7(IYD,SEC,ALT,GLAT,GLONG,STL,F107A,F107,AP,MASS,D,T) @@ -174,7 +174,7 @@ V1 =1; */ XLAT = GLAT; if ( p->SW[2] == 0 ) XLAT = 45.0; - GLATF( XLAT, &p->GSURF, &p->Rref ); + GLATF( XLAT, &p->GSURF, &p->RE ); XMM = p->PDM[5][3]; @@ -516,7 +516,7 @@ void GHP7( int IYD, double SEC, double ALT, double GLAT, double GLONG, double ST if ( (fabs(DIFF) < TEST) || (L == LTEST) ) break; XM = D[6]/(XN*1.66E-24); if ( p->IMR == 1 ) XM *= 1.0e3; - g = 1.0 + Z/p->Rref; g2 = g*g; + g = 1.0 + Z/p->RE; g2 = g*g; G = p->GSURF/g2; SH = RGAS*T[2]/(XM*G); // New altitude estimate using scale height @@ -1224,7 +1224,7 @@ void METERS( int METER, Lgm_Msis00Info *p ) { double SCALH( double ALT, double XM, double TEMP, Lgm_Msis00Info *p ) { double q, q2, G; // static double RGAS = 831.4; - q = 1.0+ALT/p->Rref; q2 = q*q; + q = 1.0+ALT/p->RE; q2 = q*q; G = p->GSURF/q2; return( RGAS*TEMP/(G*XM) ); } @@ -1672,7 +1672,7 @@ double fDENSU, Z, ZG2, TT, TA, g, g2, DTA, Z1, Z2, T1, T2, ZG, ZGDIF; double YD1, YD2, X, Y, GLB, GAMMA, EXPL, DENSA, GAMM, YI; - //ZETA(ZZ, ZL) = (ZZ-ZL)*(p->Rref+ZL)/(p->Rref+ZZ); + //ZETA(ZZ, ZL) = (ZZ-ZL)*(p->RE+ZL)/(p->RE+ZZ); //////printf("DB %g %g %g %g %g %g %g %g %g %g %g\n", ALT, DLB, TINF, TLB, XM, ALPHA, ZLB, S2, MN1, ZN1, TN1 ); fDENSU = 1.0; @@ -1693,7 +1693,7 @@ double YD1, YD2, X, Y, GLB, GAMMA, EXPL, DENSA, GAMM, YI; if ( ALT < p->ZA ) { // CALCULATE TEMPERATURE BELOW ZA // Temperature gradient at ZA from Bates profile - g = (p->Rref+ZLB)/(p->Rref+p->ZA); g2 = g*g; + g = (p->RE+ZLB)/(p->RE+p->ZA); g2 = g*g; DTA = (TINF-TA)*S2*g2; TGN1[1] = DTA ; TN1[1] = TA; @@ -1716,7 +1716,7 @@ double YD1, YD2, X, Y, GLB, GAMMA, EXPL, DENSA, GAMM, YI; // End node derivatives YD1 = -TGN1[1]/(T1*T1)*ZGDIF; - g = (p->Rref+Z2)/(p->Rref+Z1); g2 = g*g; + g = (p->RE+Z2)/(p->RE+Z1); g2 = g*g; YD2 = -TGN1[2]/(T2*T2)*ZGDIF*g2; // Calculate spline coefficients @@ -1734,7 +1734,7 @@ double YD1, YD2, X, Y, GLB, GAMMA, EXPL, DENSA, GAMM, YI; if ( XM != 0.0 ) { // CALCULATE DENSITY ABOVE ZA - g = 1.0 + ZLB/p->Rref; g2 = g*g; + g = 1.0 + ZLB/p->RE; g2 = g*g; GLB = p->GSURF/g2; GAMMA = XM*GLB/(S2*RGAS*TINF); EXPL = exp(-S2*GAMMA*ZG2); @@ -1747,7 +1747,7 @@ double YD1, YD2, X, Y, GLB, GAMMA, EXPL, DENSA, GAMM, YI; if ( ALT < p->ZA ) { // CALCULATE DENSITY BELOW ZA - g = 1.0 + Z1/p->Rref; g2 = g*g; + g = 1.0 + Z1/p->RE; g2 = g*g; GLB = p->GSURF/g2; GAMM = XM*GLB*ZGDIF/RGAS; @@ -1784,7 +1784,7 @@ double DENSM( double ALT, double D0, double XM, double *TZ, int MN3, double *ZN3 double YD2, Y2OUT[11], X, Y, GLB, GAMM, YI, EXPL; // changed this fortran statement function to a macro - //ZETA(ZZ,ZL) = (ZZ-ZL)*(p->Rref+ZL)/(p->Rref+ZZ); + //ZETA(ZZ,ZL) = (ZZ-ZL)*(p->RE+ZL)/(p->RE+ZZ); fDENSM = D0; if ( ALT <= ZN2[1] ) { @@ -1807,7 +1807,7 @@ double DENSM( double ALT, double D0, double XM, double *TZ, int MN3, double *ZN3 YD1 = -TGN2[1]/(T1*T1)*ZGDIF; - g = (p->Rref+Z2)/(p->Rref+Z1); g2 = g*g; + g = (p->RE+Z2)/(p->RE+Z1); g2 = g*g; YD2 = -TGN2[2]/(T2*T2)*ZGDIF*g2; // Calculate spline coefficients @@ -1820,7 +1820,7 @@ double DENSM( double ALT, double D0, double XM, double *TZ, int MN3, double *ZN3 if ( XM != 0.0 ) { // CALCULATE STRATOSPHERE/MESOSPHERE DENSITY - g = 1.+Z1/p->Rref; g2 = g*g; + g = 1.+Z1/p->RE; g2 = g*g; GLB = p->GSURF/g2; GAMM = XM*GLB*ZGDIF/RGAS; @@ -1851,7 +1851,7 @@ double DENSM( double ALT, double D0, double XM, double *TZ, int MN3, double *ZN3 } YD1 = -TGN3[1]/(T1*T1)*ZGDIF; - g = (p->Rref+Z2)/(p->Rref+Z1); g2 = g*g; + g = (p->RE+Z2)/(p->RE+Z1); g2 = g*g; YD2 = -TGN3[2]/(T2*T2)*ZGDIF*g2; // Calculate spline coefficients @@ -1863,7 +1863,7 @@ double DENSM( double ALT, double D0, double XM, double *TZ, int MN3, double *ZN3 *TZ = 1.0/Y; if( XM != 0.0 ) { // CALCULATE TROPOSPHERIC/STRATOSPHERE DENSITY - g = 1.0 + Z1/p->Rref; g2 = g*g; + g = 1.0 + Z1/p->RE; g2 = g*g; GLB = p->GSURF/g2; GAMM = XM*GLB*ZGDIF/RGAS; diff --git a/libLanlGeoMag/Lgm_QinDenton.c b/libLanlGeoMag/Lgm_QinDenton.c index eb3496316..606958aba 100644 --- a/libLanlGeoMag/Lgm_QinDenton.c +++ b/libLanlGeoMag/Lgm_QinDenton.c @@ -19,7 +19,6 @@ #include #include #include -#include #include "Lgm/Lgm_CTrans.h" #include "Lgm/Lgm_MagModelInfo.h" #include "Lgm/Lgm_DynamicMemory.h" @@ -541,32 +540,7 @@ void Lgm_read_QinDenton( long int Date, Lgm_QinDenton *q ) { } -/** - * \brief - * This routine interpolates the loaded Qin-Denton parameters to a given - * Julian day and poulates an Lgm_QinDentonOne structure - * - * \details - * This routine has a number of return values, which are linear sums of: - * 0 - Successful. No defaults or extrapolation. - * 1 - No data available at this time; default values returned. - * 2 - Kp data has been filled with default values. - * 4 - Dst data has been filled with default values. - * 8 - IMF data has been filled with default values. - * 16 - Velocity data has been filled with default values. - * 32 - Density/Pressure data has been filled with default values. - * 64 - Derived W parameters have been filled with default values. - * - * \param[in] JD The date/time represented as a Julian date. - * \param[in,out] p Pointer to an Lgm_QinDentonOne structure. - * \param[in] verbose A flag to set the verbosity level. - * \param[in] Persistence A flag to allow persistence population of empty fields. - * - * - * \returns int - * - */ -int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Persistence ) { +void Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Persistence ) { int t, nq, i, ny, nm, nd, nGood; double *x, *y, MJD, UTC; @@ -575,8 +549,7 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe Lgm_QinDenton *q = Lgm_init_QinDenton( Verbose ); int UsePersistence; double Wdefaults[10] = {0.44, 0.42, 0.66, 0.48, 0.49, 0.91}; //Avg values at status flag 2 (Table 3, Qin et al.) - double Gdefaults[3] = {6.0, 10.0, 60.0}; - int retval = 0, fillW = 0; + double Gdefaults[10] = {6.0, 10.0, 60.0}; UsePersistence = FALSE; MJD = JD - 2400000.5; @@ -592,7 +565,6 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe if (q->nPnts < 2) { - retval += 1; printf("Not enough QinDenton values to interpolate\n"); p->Dst = -5.0; // nT @@ -620,7 +592,6 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe p->Bz6 = 0.0; // nT } else if ( (MJD < q->MJD[0]) || (MJD > q->MJD[q->nPnts-1]) ){ - retval += 1; if (p->Persistence == 1) { UsePersistence = TRUE; @@ -681,9 +652,15 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe nq = q->nPnts; x = (double *)calloc( nq, sizeof(double) ); y = (double *)calloc( nq, sizeof(double) ); - gsl_set_error_handler_off(); + acc = gsl_interp_accel_alloc( ); + + + + + + // interpolate ByIMF for ( nGood=0, i=0; iByIMF[i] > -100.0) && (q->ByIMF[i] < 100.0) ) { @@ -718,7 +695,6 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe } else { p->BzIMF = 0.0; printf("No Good Qin Denton data in range for BzIMF. Setting BzIMF to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->BzIMF, q->MJD[0], q->MJD[q->nPnts-1], MJD); - retval += 8; } // interpolate V_SW @@ -737,10 +713,12 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe } else { p->V_SW = 400.0; printf("No Good Qin Denton data in range for V_SW. Setting V_SW to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->V_SW, q->MJD[0], q->MJD[q->nPnts-1], MJD); - retval += 16; } + + + /* * Interpolate Den_P. We really should expect (or trust) densities less than about 0.2 cm^-3. * And values less than 1 cm^-3 should be suspect.... @@ -760,10 +738,11 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe } else { p->Den_P = 1.0; printf("No Good Qin Denton data in range for Den_P. Setting Den_P to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->Den_P, q->MJD[0], q->MJD[q->nPnts-1], MJD); - retval += 32; } + + /* * Interpolate Pdyn. Since Pdyn is basned one Den_P, use Den_P as a filter on what's good. */ @@ -785,13 +764,14 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe } - // interpolate G1 + + + + // interpolate G1 -- dont yet have a good idea of what values are reasonable here... for ( nGood=0, i=0; iG1[i] > 0.0) && (q->G2[i] > 0.0) && (q->G3[i] > 0.0) ){ - x[nGood] = q->MJD[i]; - y[nGood] = q->G1[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->G1[i]; + ++nGood; } if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); @@ -799,17 +779,15 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe p->G1 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->G1 = Gdefaults[0]; + p->G1 = 0.0; printf("No Good Qin Denton data in range for G1. Setting G1 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->G1, q->MJD[0], q->MJD[q->nPnts-1], MJD); } - // interpolate G2 + // interpolate G2 -- dont yet have a good idea of what values are reasonable here... for ( nGood=0, i=0; iG1[i] > 0.0) && (q->G2[i] > 0.0) && (q->G3[i] > 0.0) ){ - x[nGood] = q->MJD[i]; - y[nGood] = q->G2[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->G2[i]; + ++nGood; } if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); @@ -817,17 +795,15 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe p->G2 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->G2 = Gdefaults[1]; + p->G2 = 0.0; printf("No Good Qin Denton data in range for G2. Setting G2 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->G2, q->MJD[0], q->MJD[q->nPnts-1], MJD); } - // interpolate G3 + // interpolate G3 -- dont yet have a good idea of what values are reasonable here... for ( nGood=0, i=0; iG1[i] > 0.0) && (q->G2[i] > 0.0) && (q->G3[i] > 0.0) ){ - x[nGood] = q->MJD[i]; - y[nGood] = q->G3[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->G3[i]; + ++nGood; } if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); @@ -835,10 +811,15 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe p->G3 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->G3 = Gdefaults[2]; + p->G3 = 0.0; printf("No Good Qin Denton data in range for G3. Setting G3 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->G3, q->MJD[0], q->MJD[q->nPnts-1], MJD); } + + + + + // interpolate Kp for ( nGood=0, i=0; ifKp[i] >= 0.0) && (q->fKp[i] <= 9.0)){ @@ -851,16 +832,10 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); gsl_spline_init( spline, x, y, nGood ); p->fKp = gsl_spline_eval( spline, MJD, acc ); - if (isnan(p->fKp)) { - p->fKp = 2.0; - printf("No Good Qin Denton data in range for Kp. Setting Kp to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->fKp, q->MJD[0], q->MJD[q->nPnts-1], MJD); - retval += 2; - } gsl_spline_free (spline); } else { p->fKp = 2.0; - printf("No Good Qin Denton data in range for Kp. Setting Kp to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->fKp, q->MJD[0], q->MJD[q->nPnts-1], MJD); - retval += 2; + printf("No Good Qin Denton data in range for fKp. Setting fKp to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->fKp, q->MJD[0], q->MJD[q->nPnts-1], MJD); } // interpolate akp3 @@ -875,10 +850,6 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); gsl_spline_init( spline, x, y, nGood ); p->akp3 = gsl_spline_eval( spline, MJD, acc ); - if (isnan(p->akp3)) { - p->akp3 = 2.0; - printf("No Good Qin Denton data in range for akp3. Setting akp3 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->akp3, q->MJD[0], q->MJD[q->nPnts-1], MJD); - } gsl_spline_free (spline); } else { p->akp3 = 2.0; @@ -897,18 +868,17 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); gsl_spline_init( spline, x, y, nGood ); p->Dst = gsl_spline_eval( spline, MJD, acc ); - if (isnan(p->Dst)) { - p->Dst = 0.0; - printf("No Good Qin Denton data in range for Dst. Setting Dst to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->Dst, q->MJD[0], q->MJD[q->nPnts-1], MJD); - retval += 4; - } gsl_spline_free (spline); } else { p->Dst = 0.0; printf("No Good Qin Denton data in range for Dst. Setting Dst to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->Dst, q->MJD[0], q->MJD[q->nPnts-1], MJD); - retval += 4; } + + + + + // interpolate Bz1 -- are these even used? for ( nGood=0, i=0; iMJD[i]; @@ -1005,13 +975,15 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe printf("No Good Qin Denton data in range for Bz6. Setting Bz6 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->Bz6, q->MJD[0], q->MJD[q->nPnts-1], MJD); } + + + + // interpolate W1 for ( nGood=0, i=0; iW1[i] > 0.0) && (q->W2[i] > 0.0) && (q->W3[i] > 0.0) && (q->W4[i] > 0.0) && (q->W5[i] > 0.0) && (q->W6[i] > 0.0)){ - x[nGood] = q->MJD[i]; - y[nGood] = q->W1[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->W1[i]; + ++nGood; } if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); @@ -1019,105 +991,94 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe p->W1 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->W1 = Wdefaults[0]; - retval += 64; - fillW = 1; + p->W1 = 0.0; printf("No Good Qin Denton data in range for W1. Setting W1 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->W1, q->MJD[0], q->MJD[q->nPnts-1], MJD); } // interpolate W2 for ( nGood=0, i=0; iW1[i] > 0.0) && (q->W2[i] > 0.0) && (q->W3[i] > 0.0) && (q->W4[i] > 0.0) && (q->W5[i] > 0.0) && (q->W6[i] > 0.0)){ - x[nGood] = q->MJD[i]; - y[nGood] = q->W2[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->W2[i]; + ++nGood; } - if ( ( nGood > 2 ) && (fillW==0) ) { + if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); gsl_spline_init( spline, x, y, nGood ); p->W2 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->W2 = Wdefaults[1]; + p->W2 = 0.0; printf("No Good Qin Denton data in range for W2. Setting W2 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->W2, q->MJD[0], q->MJD[q->nPnts-1], MJD); } // interpolate W3 for ( nGood=0, i=0; iW1[i] > 0.0) && (q->W2[i] > 0.0) && (q->W3[i] > 0.0) && (q->W4[i] > 0.0) && (q->W5[i] > 0.0) && (q->W6[i] > 0.0)){ - x[nGood] = q->MJD[i]; - y[nGood] = q->W3[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->W3[i]; + ++nGood; } - if ( ( nGood > 2 ) && (fillW==0) ) { + if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); gsl_spline_init( spline, x, y, nGood ); p->W3 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->W3 = Wdefaults[2]; + p->W3 = 0.0; printf("No Good Qin Denton data in range for W3. Setting W3 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->W3, q->MJD[0], q->MJD[q->nPnts-1], MJD); } // interpolate W4 for ( nGood=0, i=0; iW1[i] > 0.0) && (q->W2[i] > 0.0) && (q->W3[i] > 0.0) && (q->W4[i] > 0.0) && (q->W5[i] > 0.0) && (q->W6[i] > 0.0)){ - x[nGood] = q->MJD[i]; - y[nGood] = q->W4[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->W4[i]; + ++nGood; } - if ( ( nGood > 2 ) && (fillW==0) ) { + if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); gsl_spline_init( spline, x, y, nGood ); p->W4 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->W4 = Wdefaults[3]; + p->W4 = 0.0; printf("No Good Qin Denton data in range for W4. Setting W4 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->W4, q->MJD[0], q->MJD[q->nPnts-1], MJD); } // interpolate W5 for ( nGood=0, i=0; iW1[i] > 0.0) && (q->W2[i] > 0.0) && (q->W3[i] > 0.0) && (q->W4[i] > 0.0) && (q->W5[i] > 0.0) && (q->W6[i] > 0.0)){ - x[nGood] = q->MJD[i]; - y[nGood] = q->W5[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->W5[i]; + ++nGood; } - if ( ( nGood > 2 ) && (fillW==0) ) { + if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); gsl_spline_init( spline, x, y, nGood ); p->W5 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->W5 = Wdefaults[4]; + p->W5 = 0.0; printf("No Good Qin Denton data in range for W5. Setting W5 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->W5, q->MJD[0], q->MJD[q->nPnts-1], MJD); } // interpolate W6 for ( nGood=0, i=0; iW1[i] > 0.0) && (q->W2[i] > 0.0) && (q->W3[i] > 0.0) && (q->W4[i] > 0.0) && (q->W5[i] > 0.0) && (q->W6[i] > 0.0)){ - x[nGood] = q->MJD[i]; - y[nGood] = q->W6[i]; - ++nGood; - } + x[nGood] = q->MJD[i]; + y[nGood] = q->W6[i]; + ++nGood; } - if ( ( nGood > 2 ) && (fillW==0) ) { + if ( nGood > 2 ) { spline = ( nGood < 5 ) ? gsl_spline_alloc( gsl_interp_linear, nGood ) : gsl_spline_alloc( gsl_interp_akima, nGood ); gsl_spline_init( spline, x, y, nGood ); p->W6 = gsl_spline_eval( spline, MJD, acc ); gsl_spline_free (spline); } else { - p->W6 = Wdefaults[5]; + p->W6 = 0.0; printf("No Good Qin Denton data in range for W6. Setting W6 to %g. Data MJD range: [%lf, %lf], requested MJD: %lf\n", p->W6, q->MJD[0], q->MJD[q->nPnts-1], MJD); } + + free(x); free(y); - gsl_set_error_handler(NULL); gsl_interp_accel_free (acc); } @@ -1163,9 +1124,13 @@ int Lgm_get_QinDenton_at_JD( double JD, Lgm_QinDentonOne *p, int Verbose, int Pe } + + Lgm_destroy_QinDenton( q ); - return retval; + + + } void Lgm_set_QinDenton( Lgm_QinDentonOne *p, Lgm_MagModelInfo *m ) { diff --git a/libLanlGeoMag/Lgm_SphHarm.c b/libLanlGeoMag/Lgm_SphHarm.c index d35e4eb75..f99a048f7 100644 --- a/libLanlGeoMag/Lgm_SphHarm.c +++ b/libLanlGeoMag/Lgm_SphHarm.c @@ -133,7 +133,7 @@ void _Lgm_JensenCain1960( Lgm_Vector *v, Lgm_Vector *B, Lgm_CTrans *c ) { /* * Compute cos(theta), sin(theta), cos(phi), sin(phi) - * Precompute the cos(m*phi) and sin(m*phi) using recurrence relations + * Precompute the Cos(m*phi) and Sin(m*phi) using recurance relations */ st = sin( v->y ); ct = cos( v->y); sp = sin( v->z ); cp = cos( v->z ); @@ -286,7 +286,7 @@ void Lgm_InitSphHarm( int Model, double g[14][14], double h[14][14], int N, int * Compute dipole moments. */ c->M_cd = H0; - c->M_cd_McIlwain = 31165.3; + c->M_cd_McIllwain = 31165.3; c->M_cd_2010 = 29950.1686985232; c->CD_gcolat = M_PI - acos(g[1][0]/H0); diff --git a/libLanlGeoMag/Lgm_SummersDiffCoeff.c b/libLanlGeoMag/Lgm_SummersDiffCoeff.c index 7ce4b5e94..94f9534e9 100644 --- a/libLanlGeoMag/Lgm_SummersDiffCoeff.c +++ b/libLanlGeoMag/Lgm_SummersDiffCoeff.c @@ -2832,7 +2832,7 @@ if ((aStaraStarMax)) {printf("aStar=%g, aStarMin=%g, aStarMax j = computeInequalityParameters(wxl, p2.aStar, vpar, &inequalityParamsLC); j = computeInequalityParameters(wxh, p2.aStar, vpar, &inequalityParamsUC); - for (i=-20; i<=20; i++) { + for (i=-5; i<=5; i++) { p2.nCyclotronLow=(int) i; p2.nCyclotronHigh=(int) i; //printf("iCyclotron number=%d\n", i); @@ -3958,10 +3958,9 @@ int findSingleIntervalInTheta(struct inequalityParameters *params, double dw, in int Lgm_SimpleRiemannSum( double (*f)(double, _qpInfo *), _qpInfo *args, double xleft, double xright, double *result, int VerbosityLevel ) { - int nIntervals, nSubIntervals, i, i2; - double x,sum,dx, epsabs=0.0, epsrel=0.1,abserr, thisf; + int nIntervals, nSubIntervals, i; + double x,sum,dx, epsabs=0.0, epsrel=0.1,abserr; size_t neval; - //gsl_error_handler_t *gslHandler; /* Approach #1: use a simple Riemann sum nIntervals = 100; @@ -3991,32 +3990,9 @@ int Lgm_SimpleRiemannSum( double (*f)(double, _qpInfo *), _qpInfo *args, double F.function = f; F.params = args; *result=0.0; -/* Turn GSL's default error handling (which aborts upon seeing an error) off so that I can handle the error by dumping out the values */ - //gslHandler = (gsl_error_handler_t *) gsl_set_error_handler_off(); - i2 = (int) gsl_integration_qag(&F, xleft, xright, epsabs, epsrel, (size_t) nSubIntervals, GSL_INTEG_GAUSS21, w, result, &abserr); - if (i2 != 0) - { - nIntervals = 100; - - dx = (xright-xleft)/((double) nIntervals); - sum = 0.0; - for (i=0; i2.0)) - { - printf("GSL error in gsl_integration_qag: return flag=%d, xleft=%g, xright=%g, epsrel=%g, w->size=%d, result=%g, abserr=%g. Simple Riemann sum with 100 uniform samples produces %g, which is being returned but is more than 2s different than GSL result\n", i2, xleft, xright, epsrel, w->size, *result, abserr, sum); - } - *result = sum; - } -/* Turn GSL's default error handling (which aborts upon seeing an error) back on*/ - //gslHandler = (gsl_error_handler_t *) gsl_set_error_handler(NULL); + gsl_integration_qag(&F, xleft, xright, epsabs, epsrel, (size_t) nSubIntervals, GSL_INTEG_GAUSS21, w, result, &abserr); // printf("Number of evaluations needed by adaptive Gauss-Kronrod 21-point quadrature to achieve %g relative accuracy is %d, abserr is %g and integral is %g\n", epsrel, w->size, abserr, *result); - i = w->size; gsl_integration_workspace_free(w); - return(i); + return(w->size); } diff --git a/libLanlGeoMag/Lgm_Trace.c b/libLanlGeoMag/Lgm_Trace.c index 784a8b583..bd83e67cb 100644 --- a/libLanlGeoMag/Lgm_Trace.c +++ b/libLanlGeoMag/Lgm_Trace.c @@ -105,7 +105,7 @@ */ int Lgm_Trace( Lgm_Vector *u, Lgm_Vector *v1, Lgm_Vector *v2, Lgm_Vector *v3, double Height, double TOL1, double TOL2, Lgm_MagModelInfo *Info ) { - int i, reset, flag1, flag2, flag3, InitiallyBelowTargetHeight, done; + int i, reset, flag1, flag2, InitiallyBelowTargetHeight, done; double sgn=1.0, R, Rtarget, Rinitial, Rplus, H, Hinitial; Lgm_Vector w, Bvec; double h, h_inv, h2_inv, F[7], Px[7], Py[7], Pz[7], s, Hdid, Hnext, Htry; @@ -252,14 +252,7 @@ double MIKEB = Info->Trace_s; */ //Lgm_TraceToMinBSurf( v1, v3, TOL1, TOL2, Info ); //Lgm_TraceToMinBSurf( v1, v3, 0.1, TOL2, Info ); - /* - * Check the result of Lgm_TraceToMinBSurf to make sure it returns a closed field line - */ - flag3 = Lgm_TraceToMinBSurf( u, v3, 0.1, TOL2, Info ); - if (flag3 != LGM_CLOSED) { - printf("Major problem in Lgm_Trace(): northern and southern footpoints found, but TraceToMinBSurf does not return LGM_CLOSED, rather returns %d. Returning %d.\n", flag3, flag3); - return(flag3); - } + Lgm_TraceToMinBSurf( u, v3, 0.1, TOL2, Info ); Info->v3_final = *v3; Info->Pmin = *v3; //Info->Smin = Info->Trace_s; // save location of Bmin. NOTE: Smin is measured from the southern footpoint. diff --git a/libLanlGeoMag/Lgm_TraceToSphericalEarth.c b/libLanlGeoMag/Lgm_TraceToSphericalEarth.c index 8956cda42..5fd51e1e3 100644 --- a/libLanlGeoMag/Lgm_TraceToSphericalEarth.c +++ b/libLanlGeoMag/Lgm_TraceToSphericalEarth.c @@ -89,19 +89,22 @@ int Lgm_TraceToSphericalEarth( Lgm_Vector *u, Lgm_Vector *v, double TargetHeight * */ if ( Rinitial < WGS84_B ) { + // must be inside the Earth, which is no good -- bail with // LGM_INSIDE_EARTH error code - return( LGM_INSIDE_EARTH ); //LGM_INSIDE_EARTH = -1 + return( LGM_INSIDE_EARTH ); } else { + // We are at least at or above WGS84_B. We could still be in trouble in // terms of being inside the Earth, so we have to check more // thouroughly now. Determine Geodetic Height Lgm_WGS84_to_GeodHeight( u, &Height ); if ( Height < 0.0 ) { + // inside the Earth, which is no good -- bail with error - return( LGM_INSIDE_EARTH ); //LGM_INSIDE_EARTH = -1 + return( LGM_INSIDE_EARTH ); } @@ -127,11 +130,13 @@ int Lgm_TraceToSphericalEarth( Lgm_Vector *u, Lgm_Vector *v, double TargetHeight Pc.x = Pc.y = Pc.z = 0.0; P = *u; Hmax = Info->Hmax; +Hmax = 1.0; + Hmin = 0.001; Hmin = 1e-8; u_scale.x = u_scale.y = u_scale.z = 1.0; Height = Height_a = Height_b = Height_c = 0.0; F = Fa = Fb = Fc = 0.0; -//printf("\nHmax = %g\n", Hmax); + //printf("\nHmax = %g\n", Hmax); @@ -158,6 +163,7 @@ int Lgm_TraceToSphericalEarth( Lgm_Vector *u, Lgm_Vector *v, double TargetHeight StartHeight = Height; if ( !AboveTargetHeight ){ + /* * Determine which direction along the field line will take us higher. */ @@ -193,7 +199,7 @@ int Lgm_TraceToSphericalEarth( Lgm_Vector *u, Lgm_Vector *v, double TargetHeight done = TRUE; } else if ( Height < StartHeight ) { // We are going back down again -- Target Height unreachable? -- Bail out - return( LGM_TARGET_HEIGHT_UNREACHABLE ); //LGM_TARGET_HEIGHT_UNREACHABLE=-2 + return( LGM_TARGET_HEIGHT_UNREACHABLE ); } } @@ -205,6 +211,7 @@ int Lgm_TraceToSphericalEarth( Lgm_Vector *u, Lgm_Vector *v, double TargetHeight + /* * Bracket the zero first. * We want to stop in the ionosphere at a certain height above the Earth @@ -234,7 +241,6 @@ int Lgm_TraceToSphericalEarth( Lgm_Vector *u, Lgm_Vector *v, double TargetHeight Htry = 0.9*Height_a; // This computes Htry as 90% of the distance to the Earth's surface (could be small if we are already close!) if (Htry > Hmax) Htry = Hmax; // If its bigger than Hmax reset it to Hmax -- to be safe. -//printf("1. PPPPPPPPPP = %g %g %g; Height_a = %g; Fa = %g; Htry = %g\n", P.x, P.y, P.z, Height_a, Fa, Htry); /* @@ -296,7 +302,7 @@ int Lgm_TraceToSphericalEarth( Lgm_Vector *u, Lgm_Vector *v, double TargetHeight //printf("C. Htry = %g\n", Htry); if ( Count > 1000) { - if (Info->VerbosityLevel > 0) printf("File: %s Lgm_TraceToSphericalEarth(), Line: %d; Too many iterations trying to reach target height (are we in a weird field region?) Returning with -1.\n", __FILE__, __LINE__ ); + printf("File: %s Lgm_TraceToSphericalEarth(), Line: %d; Too many iterations trying to reach target height (are we in a weird field region?) Returning with -1.\n", __FILE__, __LINE__ ); //exit(0); return(-1); } @@ -305,7 +311,7 @@ int Lgm_TraceToSphericalEarth( Lgm_Vector *u, Lgm_Vector *v, double TargetHeight } if ( ((Fc > 0.0) && (Fa > 0.0)) || ((Fc < 0.0) && (Fa < 0.0)) ) { - // No bracket -- can't reach target height somehow?? + // No bracket return(0); } @@ -344,6 +350,7 @@ if (1==1){ Htry = 0.5*fabs(d); // LGM_1M_1O_GOLD is 0.381966... // } if ( Lgm_MagStep( &P, &u_scale, Htry, &Hdid, &Hnext, sgn, &s, &reset, Info->Bfield, Info ) < 0 ) return(-1); +//printf("3. PPPPPPPPPP = %g %g %g HTRY = %g\n", P.x, P.y, P.z, Htry); Height = WGS84_A*(Lgm_Magnitude( &P )-1.0); F = Height - TargetHeight; if ( F >= 0.0 ) { diff --git a/libLanlGeoMag/MagStep.c b/libLanlGeoMag/MagStep.c index db5e6a665..956a9ee44 100644 --- a/libLanlGeoMag/MagStep.c +++ b/libLanlGeoMag/MagStep.c @@ -20,24 +20,26 @@ #define FMIN(a,b) (((a)<(b))?(a):(b)) int Lgm_MagStep( Lgm_Vector *u, Lgm_Vector *u_scale, - double Htry, double *Hdid, double *Hnext, - double sgn, double *s, int *reset, - int (*Mag)(Lgm_Vector *, Lgm_Vector *, Lgm_MagModelInfo *), Lgm_MagModelInfo *Info ){ + double Htry, double *Hdid, double *Hnext, + double sgn, double *s, int *reset, + int (*Mag)(Lgm_Vector *, Lgm_Vector *, Lgm_MagModelInfo *), Lgm_MagModelInfo *Info ){ Lgm_Vector u0; double eps; - int status = 1; u0 = *u; if ( Info->Lgm_MagStep_Integrator == LGM_MAGSTEP_ODE_BS ) { +//printf("Info->Lgm_MagStep_BS_Eps = %g\b", Info->Lgm_MagStep_BS_Eps); +//exit(0); +//Info->Lgm_MagStep_BS_Eps = 1e-7; eps = Info->Lgm_MagStep_BS_Eps; - status = Lgm_MagStep_BS( u, u_scale, Htry, Hdid, Hnext, eps, sgn, s, reset, Mag, Info ); + Lgm_MagStep_BS( u, u_scale, Htry, Hdid, Hnext, eps, sgn, s, reset, Mag, Info ); } else if ( Info->Lgm_MagStep_Integrator == LGM_MAGSTEP_ODE_RK5 ) { eps = Info->Lgm_MagStep_RK5_Eps; - status = Lgm_MagStep_RK5( u, u_scale, Htry, Hdid, Hnext, eps, sgn, s, reset, Mag, Info ); + Lgm_MagStep_RK5( u, u_scale, Htry, Hdid, Hnext, eps, sgn, s, reset, Mag, Info ); } else { @@ -47,7 +49,7 @@ int Lgm_MagStep( Lgm_Vector *u, Lgm_Vector *u_scale, } - return(status); + return(1); } @@ -341,7 +343,7 @@ int Lgm_MagStep_BS( Lgm_Vector *u, Lgm_Vector *u_scale, scale[0] = u_scale->x; scale[1] = u_scale->y; scale[2] = u_scale->z; if ( fabs(htry) < 1e-16 ) { - printf("%s(): Requested stepsize is very small (returning with -1). htry = %g\n", __func__, htry ); + printf("Lgm_MagStep(): Requested stepsize is very small (returning with -1). htry = %g\n", htry ); return(-1); } @@ -379,14 +381,14 @@ int Lgm_MagStep_BS( Lgm_Vector *u, Lgm_Vector *u_scale, u0 = *u; if ( (*Mag)(&u0, &b0, Info) == 0 ) { // bail if B-field eval had issues. - printf("%s(): B-field evaluation at u0 = %g %g %g returned with errors (returning with -1)\n", __func__, u0.x, u0.y, u0.z ); + printf("Lgm_MagStep(): B-field evaluation at u0 = %g %g %g returned with errors (returning with -1)\n", u0.x, u0.y, u0.z ); return(-1); } ++(Info->Lgm_nMagEvals); Bmag = Lgm_NormalizeVector(&b0); if ( Bmag < 1e-16 ) { // bail if B-field magnitude is too small - printf("%s(): Bmag too small at u0 = %g %g %g (Bmag = %g; Bx,y,z = %g, %g, %g) (returning with -1).\n", __func__, u0.x, u0.y, u0.z, Bmag, b0.x, b0.y, b0.z ); + printf("Lgm_MagStep(): Bmag too small at u0 = %g %g %g (Bmag = %g; Bx,y,z = %g, %g, %g) (returning with -1).\n", u0.x, u0.y, u0.z, Bmag, b0.x, b0.y, b0.z ); //printf("Line %d\n", __LINE__ ); //exit(-1); return(-1); @@ -528,6 +530,9 @@ Info->Lgm_MagStep_BS_last_step = FALSE; + + + // Determine optimal order for next step. if ( k == 1 ) { kopt = 2; diff --git a/libLanlGeoMag/Makefile.am b/libLanlGeoMag/Makefile.am index dc7b3a465..94a3a3303 100644 --- a/libLanlGeoMag/Makefile.am +++ b/libLanlGeoMag/Makefile.am @@ -53,10 +53,11 @@ libLanlGeoMag_la_SOURCES = Lgm_AlphaOfK.c Lgm_DFI_RBF.c Lgm_Vec_RBF.c Lgm_B_Fro libLanlGeoMag_la_LDFLAGS = $(AM_LDFLAGS) @PERL_LDFLAGS@ @OPENMP_CFLAGS@ -libLanlGeoMag_la_CFLAGS = $(AM_CFLAGS) @PERL_CFLAGS@ @OPENMP_CFLAGS@ +libLanlGeoMag_la_CFLAGS = $(AM_CFLAGS) @PERL_CFLAGS@ @OPENMP_CFLAGS@ -Wno-incompatible-pointer-types -Wno-implicit-function-declaration -Wno-int-conversion libLanlGeoMag_la_CPPFLAGS = $(AM_CPPFLAGS) -DDATADIR=\"$(datadir)\" -DHASH_FUNCTION=HASH_SFH -DHASH_BLOOM=32 @PERL_CPPFLAGS@ -EXTRA_DIST = TS07D_FILES DE_FILES Images Stars +#EXTRA_DIST = TS07D_FILES DE_FILES Images Stars +EXTRA_DIST = TS07D_FILES DE_FILES Stars install-data-hook: if ENABLE_INDICES @@ -67,11 +68,11 @@ if ENABLE_INDICES $(MKDIR_P) $(DESTDIR)$(LGM_DE_DATA_DIR) $(RSYNC_CMD) -arv $(srcdir)/DE_FILES $(DESTDIR)$(LGM_DE_DATA_DIR)/. @echo Additional DE files should be placed in $(DESTDIR)$(LGM_DE_DATA_DIR) - $(MKDIR_P) $(DESTDIR)$(LGM_IMAGE_DATA_DIR) - $(RSYNC_CMD) -arv $(srcdir)/Images/* $(DESTDIR)$(LGM_IMAGE_DATA_DIR)/. # should cover BlueMarble stuff also. $(MKDIR_P) $(DESTDIR)$(LGM_STARS_DATA_DIR) $(RSYNC_CMD) -arv $(srcdir)/Stars/* $(DESTDIR)$(LGM_STARS_DATA_DIR)/. endif +# # $(MKDIR_P) $(DESTDIR)$(LGM_IMAGE_DATA_DIR) +# # $(RSYNC_CMD) -arv $(srcdir)/Images/* $(DESTDIR)$(LGM_IMAGE_DATA_DIR)/. # should cover BlueMarble stuff also. uninstall-hook: if ENABLE_INDICES diff --git a/libLanlGeoMag/lgm.pc.in b/libLanlGeoMag/lgm.pc.in index 5909414cf..908e94b65 100644 --- a/libLanlGeoMag/lgm.pc.in +++ b/libLanlGeoMag/lgm.pc.in @@ -9,4 +9,4 @@ URL: Version: @PACKAGE_VERSION@ Requires: gsl Libs: -Wl,-rpath,${libdir} @LDFLAGS@ -L${libdir} -lLanlGeoMag -lgsl -lgslcblas -lm @OPENMP_CFLAGS@ @HDF5_LDFLAGS@ -lhdf5 -Cflags: @CFLAGS@ -I${includedir} -I${includedir}/Lgm -g -Wall -O3 -funroll-all-loops -ffast-math @OPENMP_CFLAGS@ @HDF5_CFLAGS@ +Cflags: -I${includedir} -I${includedir}/Lgm @OPENMP_CFLAGS@ @HDF5_CFLAGS@ diff --git a/tests/Makefile.am b/tests/Makefile.am index 99799e3a3..5f8255f39 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -1,29 +1,23 @@ ## Process this file with automake to produce Makefile.in lgm_includes=$(top_srcdir)/libLanlGeoMag/Lgm/ -check_PROGRAMS = check_libLanlGeoMag check_ClosedField check_McIlwain_L check_PolyRoots check_Magmodels check_Sgp4 check_DE421 check_CoordTrans check_IsoTimeStringToDateTime check_Lstar -TESTS = check_libLanlGeoMag check_ClosedField check_McIlwain_L check_PolyRoots check_Magmodels check_Sgp4 check_DE421 check_CoordTrans check_IsoTimeStringToDateTime check_Lstar +#check_PROGRAMS = check_libLanlGeoMag check_IsoTimeStringToDateTime check_McIlwain_L check_PolyRoots check_Sgp4 +#TESTS = check_libLanlGeoMag check_IsoTimeStringToDateTime check_McIlwain_L check_PolyRoots check_Sgp4 +check_PROGRAMS = check_libLanlGeoMag check_McIlwain_L check_PolyRoots check_Sgp4 +TESTS = check_libLanlGeoMag check_McIlwain_L check_PolyRoots check_Sgp4 check_libLanlGeoMag_SOURCES = check_libLanlGeoMag.c $(lgm_includes)/Lgm_CTrans.h check_libLanlGeoMag_CFLAGS = @CHECK_CFLAGS@ check_libLanlGeoMag_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @CHECK_LIBS@ -check_ClosedField_SOURCES = check_ClosedField.c $(lgm_includes)/Lgm_CTrans.h $(lgm_includes)/Lgm_MagModelInfo.h -check_ClosedField_CFLAGS = @CHECK_CFLAGS@ -check_ClosedField_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @PERL_LDFLAGS@ @CHECK_LIBS@ - -check_IsoTimeStringToDateTime_SOURCES = check_IsoTimeStringToDateTime.c $(lgm_includes)/Lgm_CTrans.h -check_IsoTimeStringToDateTime_CFLAGS = @CHECK_CFLAGS@ -check_IsoTimeStringToDateTime_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @PERL_LDFLAGS@ @CHECK_LIBS@ +#check_IsoTimeStringToDateTime_SOURCES = check_IsoTimeStringToDateTime.c $(lgm_includes)/Lgm_CTrans.h +#check_IsoTimeStringToDateTime_CFLAGS = @CHECK_CFLAGS@ +#check_IsoTimeStringToDateTime_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @CHECK_LIBS@ check_McIlwain_L_SOURCES = check_McIlwain_L.c $(lgm_includes)/Lgm_CTrans.h check_McIlwain_L_CFLAGS = @CHECK_CFLAGS@ check_McIlwain_L_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @CHECK_LIBS@ -check_Lstar_SOURCES = check_Lstar.c $(lgm_includes)/Lgm_CTrans.h $(lgm_includes)/Lgm_LstarInfo.h $(lgm_includes)/Lgm_MagEphemInfo.h -check_Lstar_CFLAGS = @CHECK_CFLAGS@ -fopenmp -check_Lstar_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @PERL_LDFLAGS@ @CHECK_LIBS@ - check_PolyRoots_SOURCES = check_PolyRoots.c $(lgm_includes)/Lgm_CTrans.h check_PolyRoots_CFLAGS = @CHECK_CFLAGS@ check_PolyRoots_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @CHECK_LIBS@ @@ -32,16 +26,4 @@ check_Sgp4_SOURCES = check_Sgp4.c $(lgm_includes)/Lgm_CTrans.h check_Sgp4_CFLAGS = @CHECK_CFLAGS@ check_Sgp4_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @CHECK_LIBS@ -check_Magmodels_SOURCES = check_Magmodels.c $(lgm_includes)/Lgm_CTrans.h $(lgm_includes)/Lgm_MagModelInfo.h -check_Magmodels_CFLAGS = @CHECK_CFLAGS@ -check_Magmodels_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @PERL_LDFLAGS@ @CHECK_LIBS@ - -check_DE421_SOURCES = check_DE421.c $(lgm_includes)/Lgm_CTrans.h $(lgm_includes)/Lgm_Vec.h -check_DE421_CFLAGS = @CHECK_CFLAGS@ -check_DE421_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @CHECK_LIBS@ - -check_CoordTrans_SOURCES = check_CoordTrans.c $(lgm_includes)/Lgm_CTrans.h $(lgm_includes)/Lgm_Vec.h -check_CoordTrans_CFLAGS = @CHECK_CFLAGS@ -check_CoordTrans_LDADD = $(top_builddir)/libLanlGeoMag/.libs/libLanlGeoMag.a @PERL_LDFLAGS@ @CHECK_LIBS@ - -EXTRA_DIST = check_Lstar.expected check_McIlwain_L_01.expected check_McIlwain_L_02.expected check_McIlwain_L_03.expected check_McIlwain_L_04.expected check_McIlwain_L_05.expected check_McIlwain_L_06.expected check_McIlwain_L_07.expected check_McIlwain_L_08.expected check_PolyRoots_01.expected check_PolyRoots_02.expected check_PolyRoots_03.expected check_PolyRoots_04.expected check_Sgp4_01.expected testpo.421 check_CoordTrans.expected check_CoordTransNoEph.expected check_CoordDipoleTilt.expected check_Magmodels_01.expected check_ClosedField_01.expected +EXTRA_DIST = check_McIlwain_L_01.expected check_McIlwain_L_02.expected check_McIlwain_L_03.expected check_McIlwain_L_04.expected check_PolyRoots_01.expected check_PolyRoots_02.expected check_PolyRoots_03.expected check_PolyRoots_04.expected check_Sgp4_01.expected diff --git a/tests/check_McIlwain_L.c b/tests/check_McIlwain_L.c index e63176ede..3cbc3caf7 100644 --- a/tests/check_McIlwain_L.c +++ b/tests/check_McIlwain_L.c @@ -11,11 +11,13 @@ Lgm_CTrans *c; void McIlwain_L_Setup(void) { mInfo = Lgm_InitMagInfo(); + c = Lgm_init_ctrans( 0 ); return; } void McIlwain_L_TearDown(void) { Lgm_FreeMagInfo( mInfo ); + Lgm_free_ctrans( c ) ; return; } @@ -41,9 +43,9 @@ START_TEST(test_MCILWAIN_01) { } - Date = 20090101; UTC = 0.0; mInfo->Kp = 2; Lgm_Set_Coord_Transforms( Date, UTC, mInfo->c ); + Date = 20090101; UTC = 0.0; mInfo->Kp = 2; Lgm_Set_Coord_Transforms( Date, UTC, c ); u.x = -4.0; u.y = 0.0; u.z = 0.0; - Lgm_Convert_Coords( &u, &v, SM_TO_GSM, mInfo->c ); + Lgm_Convert_Coords( &u, &v, SM_TO_GSM, c ); Lgm_MagModelInfo_Set_MagModel( LGM_CDIP, LGM_EXTMODEL_NULL, mInfo ); L = Lgm_McIlwain_L( Date, UTC, &v, 90.0, 0, &I, &Bm, &M, mInfo ); @@ -82,6 +84,8 @@ START_TEST(test_MCILWAIN_02) { FILE *fp_got; if ( (fp_expected = fopen( "check_McIlwain_L_02.expected", "r" )) != NULL ) { +printf("HERe\n"); + fscanf( fp_expected, "%lf", &L_expected ); fscanf( fp_expected, "%lf", &I_expected ); fscanf( fp_expected, "%lf", &Bm_expected ); @@ -91,12 +95,12 @@ START_TEST(test_MCILWAIN_02) { printf("Lgm_McIlwain_L(): Cant open file: check_McIlwain_L_02.expected\n" ); } - Date = 20090101; UTC = 0.0; mInfo->Kp = 2; Lgm_Set_Coord_Transforms( Date, UTC, mInfo->c ); + Date = 20090101; UTC = 0.0; mInfo->Kp = 2; Lgm_Set_Coord_Transforms( Date, UTC, c ); u.x = -6.6; u.y = 2.3; u.z = 0.4; - Lgm_MagModelInfo_Set_MagModel( LGM_IGRF, LGM_EXTMODEL_T89, mInfo ); L = Lgm_McIlwain_L( Date, UTC, &u, 90.0, 1, &I, &Bm, &M, mInfo ); if ( (fabs( L-L_expected ) < 1e-7) && (fabs( I-I_expected ) < 1e-7) && (fabs( Bm-Bm_expected ) < 1e-7) && (fabs( M-M_expected ) < 1e-7) ) Passed = TRUE; +printf("HERE Passed = %d\n", Passed); if ( !Passed ){ printf("\nTest 02, Lgm_McIlwain_L(): %15s %15s %15s %15s\n", " L ", " I ", " Bm ", " M "); printf(" Expected: %.15g %.15g %.15g %.15g\n", L_expected, I_expected, Bm_expected, M_expected ); @@ -142,14 +146,13 @@ START_TEST(test_MCILWAIN_03) { printf("Lgm_McIlwain_L(): Cant open file: check_McIlwain_L_03.expected\n" ); } - Date = 20060823; UTC = 13.213; mInfo->Kp = 5; Lgm_Set_Coord_Transforms( Date, UTC, mInfo->c ); + Date = 20060823; UTC = 13.213; mInfo->Kp = 5; Lgm_Set_Coord_Transforms( Date, UTC, c ); u.x = 2.4; u.y = 1.2; u.z = 0.4; - Lgm_MagModelInfo_Set_MagModel( LGM_IGRF, LGM_EXTMODEL_T89c, mInfo ); L = Lgm_McIlwain_L( Date, UTC, &u, 90.0, 1, &I, &Bm, &M, mInfo ); if ( (fabs( L-L_expected ) < 1e-7) && (fabs( I-I_expected ) < 1e-7) && (fabs( Bm-Bm_expected ) < 1e-7) && (fabs( M-M_expected ) < 1e-7) ) Passed = TRUE; if ( !Passed ){ - printf("\nTest 03, Lgm_McIlwain_L(): %15s %15s %15s %15s\n", " L ", " I ", " Bm ", " M "); + printf("\nTest 02, Lgm_McIlwain_L(): %15s %15s %15s %15s\n", " L ", " I ", " Bm ", " M "); printf(" Expected: %.15g %.15g %.15g %.15g\n", L_expected, I_expected, Bm_expected, M_expected ); printf(" Got: %.15g %.15g %.15g %.15g\n\n\n", L, I, Bm, M); } @@ -193,10 +196,8 @@ START_TEST(test_MCILWAIN_04) { } - Date = 20090101; UTC = 0.0; mInfo->Kp = 2; Lgm_Set_Coord_Transforms( Date, UTC, mInfo->c ); + Date = 20090101; UTC = 0.0; mInfo->Kp = 2; Lgm_Set_Coord_Transforms( Date, UTC, c ); u.x = -7.0; u.y = 1.0; u.z = 2.0; - //Lgm_Convert_Coords( &u, &v, SM_TO_GSM, mInfo->c ); - Lgm_MagModelInfo_Set_MagModel( LGM_IGRF, LGM_EXTMODEL_T89, mInfo ); L = Lgm_McIlwain_L( Date, UTC, &u, 90.0, 1, &I, &Bm, &M, mInfo ); if ( (fabs( L-L_expected ) < 1e-7) && (fabs( I-I_expected ) < 1e-7) && (fabs( Bm-Bm_expected ) < 1e-7) && (fabs( M-M_expected ) < 1e-7) ) Passed = TRUE; @@ -224,231 +225,7 @@ START_TEST(test_MCILWAIN_04) { } END_TEST -START_TEST(test_MCILWAIN_05) { - - int Passed = FALSE; - long int Date; - double L, I, Bm, M, UTC; - double L_expected=-9e99, I_expected=-9e99, Bm_expected=-9e99, M_expected=-9e99; - Lgm_Vector u, v; - FILE *fp_expected; - FILE *fp_got; - - if ( (fp_expected = fopen( "check_McIlwain_L_05.expected", "r" )) != NULL ) { - fscanf( fp_expected, "%lf", &L_expected ); - fscanf( fp_expected, "%lf", &I_expected ); - fscanf( fp_expected, "%lf", &Bm_expected ); - fscanf( fp_expected, "%lf", &M_expected ); - fclose( fp_expected ); - } else { - printf("Lgm_McIlwain_L(): Cant open file: check_McIlwain_L_05.expected\n" ); - } - - - Date = 20090101; UTC = 0.0; - Lgm_Set_Coord_Transforms( Date, UTC, mInfo->c ); - u.x = -7.0; u.y = 0.0; u.z = 0.0; - Lgm_Convert_Coords( &u, &v, SM_TO_GSM, mInfo->c ); - Lgm_MagModelInfo_Set_MagModel( LGM_CDIP, LGM_EXTMODEL_NULL, mInfo ); - L = Lgm_McIlwain_L( Date, UTC, &v, 90.0, 1, &I, &Bm, &M, mInfo ); - - if ( (fabs( L-L_expected ) < 1e-7) && (fabs( I-I_expected ) < 1e-7) && (fabs( Bm-Bm_expected ) < 1e-7) && (fabs( M-M_expected ) < 1e-7) ) Passed = TRUE; - if ( !Passed ){ - - printf("\nTest 05, Lgm_McIlwain_L(): %15s %15s %15s %15s\n", " L ", " I ", " Bm ", " M "); - printf(" Expected: %.15g %.15g %.15g %.15g\n", L_expected, I_expected, Bm_expected, M_expected ); - printf(" Got: %.15g %.15g %.15g %.15g\n\n\n", L, I, Bm, M); - } - - if ( (fp_got = fopen( "check_McIlwain_L_05.got", "w" )) != NULL ) { - fprintf( fp_got, "%.15lf\n", L ); - fprintf( fp_got, "%.15lf\n", I ); - fprintf( fp_got, "%.15lf\n", Bm ); - fprintf( fp_got, "%.15lf\n", M ); - fclose( fp_got ); - } else { - printf("Could not open file: check_McIlwain_L_05.got\\n"); - } - - fail_unless( Passed, "Lgm_McIlwain_L(): Regression test failed. Compare 'expected' and 'got' files: check_McIlwain_L_05.expected check_McIlwain_L_05.got\n" ); - - - return; -} -END_TEST - -START_TEST(test_MCILWAIN_06) { - - int Passed = FALSE; - long int Date; - double L, I, Bm, M, UTC, Bmin, Blocal; - double L_expected=-9e99, I_expected=-9e99, Bm_expected=-9e99, M_expected=-9e99, Bmin_expected=-9e99, Blocal_expected=-9e99; - Lgm_Vector u, v; - FILE *fp_expected; - FILE *fp_got; - - if ( (fp_expected = fopen( "check_McIlwain_L_06.expected", "r" )) != NULL ) { - - fscanf( fp_expected, "%lf", &L_expected ); - fscanf( fp_expected, "%lf", &I_expected ); - fscanf( fp_expected, "%lf", &Bm_expected ); - fscanf( fp_expected, "%lf", &M_expected ); - fscanf( fp_expected, "%lf", &Blocal_expected ); - fscanf( fp_expected, "%lf", &Bmin_expected ); - fclose( fp_expected ); - } else { - printf("Lgm_McIlwain_L(): Cant open file: check_McIlwain_L_06.expected\n" ); - } - - - Date = 20090101; UTC = 0.0; - Lgm_Set_Coord_Transforms( Date, UTC, mInfo->c ); - u.x = -4.0; u.y = 0.0; u.z = 1.0; - Lgm_Convert_Coords( &u, &v, GSM_TO_GSM, mInfo->c ); - Lgm_MagModelInfo_Set_MagModel( LGM_IGRF, LGM_EXTMODEL_T89, mInfo ); - L = Lgm_McIlwain_L( Date, UTC, &v, 90.0, 1, &I, &Bm, &M, mInfo ); - Blocal = mInfo->Blocal; - Bmin = mInfo-> Bmin; - - if ( (fabs( L-L_expected ) < 1e-7) && (fabs( I-I_expected ) < 1e-7) && (fabs( Bm-Bm_expected ) < 1e-7) && (fabs( M-M_expected ) < 1e-7) && (fabs( Blocal-Blocal_expected ) < 1e-7) && (fabs( Bmin-Bmin_expected ) < 1e-7)) Passed = TRUE; - if ( !Passed ){ - - printf("\nTest 06, Lgm_McIlwain_L(): %15s %15s %15s %15s\n", " L ", " I ", " Bm ", " M "); - printf(" Expected: %.15g %.15g %.15g %.15g %.15g %.15g\n", L_expected, I_expected, Bm_expected, M_expected, Blocal_expected, Bmin_expected); - printf(" Got: %.15g %.15g %.15g %.15g %.15g %.15g\n\n\n", L, I, Bm, M, Blocal, Bmin); - } - - if ( (fp_got = fopen( "check_McIlwain_L_06.got", "w" )) != NULL ) { - fprintf( fp_got, "%.15lf\n", L ); - fprintf( fp_got, "%.15lf\n", I ); - fprintf( fp_got, "%.15lf\n", Bm ); - fprintf( fp_got, "%.15lf\n", M ); - fprintf( fp_got, "%.15lf\n", Blocal ); - fprintf( fp_got, "%.15lf\n", Bmin ); - fclose( fp_got ); - } else { - printf("Could not open file: check_McIlwain_L_06.got\\n"); - } - - fflush(stdout); - fail_unless( Passed, "Lgm_McIlwain_L(): Regression test failed. Compare 'expected' and 'got' files: check_McIlwain_L_06.expected check_McIlwain_L_06.got\n" ); - - - return; -} -END_TEST - -START_TEST(test_MCILWAIN_07) { - - int Passed = FALSE; - long int Date; - double L, I, Bm, M, UTC; - double L_expected=-9e99, I_expected=-9e99, Bm_expected=-9e99, M_expected=-9e99; - Lgm_Vector u, v; - FILE *fp_expected; - FILE *fp_got; - - if ( (fp_expected = fopen( "check_McIlwain_L_07.expected", "r" )) != NULL ) { - - fscanf( fp_expected, "%lf", &L_expected ); - fscanf( fp_expected, "%lf", &I_expected ); - fscanf( fp_expected, "%lf", &Bm_expected ); - fscanf( fp_expected, "%lf", &M_expected ); - fclose( fp_expected ); - } else { - printf("Lgm_McIlwain_L(): Cant open file: check_McIlwain_L_07.expected\n" ); - } - - - Date = 20090101; UTC = 0.0; - Lgm_Set_Coord_Transforms( Date, UTC, mInfo->c ); - u.x = -4.0; u.y = 0.0; u.z = 1.0; - Lgm_Convert_Coords( &u, &v, SM_TO_GSM, mInfo->c ); - Lgm_MagModelInfo_Set_MagModel( LGM_IGRF, LGM_EXTMODEL_T89, mInfo ); - L = Lgm_McIlwain_L( Date, UTC, &v, 90.0, 1, &I, &Bm, &M, mInfo ); - - if ( (fabs( L-L_expected ) < 1e-7) && (fabs( I-I_expected ) < 1e-7) && (fabs( Bm-Bm_expected ) < 1e-7) && (fabs( M-M_expected ) < 1e-7) ) Passed = TRUE; - if ( !Passed ){ - - printf("\nTest 07, Lgm_McIlwain_L(): %15s %15s %15s %15s\n", " L ", " I ", " Bm ", " M "); - printf(" Expected: %.15g %.15g %.15g %.15g\n", L_expected, I_expected, Bm_expected, M_expected ); - printf(" Got: %.15g %.15g %.15g %.15g\n\n\n", L, I, Bm, M); - } - - if ( (fp_got = fopen( "check_McIlwain_L_07.got", "w" )) != NULL ) { - fprintf( fp_got, "%.15lf\n", L ); - fprintf( fp_got, "%.15lf\n", I ); - fprintf( fp_got, "%.15lf\n", Bm ); - fprintf( fp_got, "%.15lf\n", M ); - fclose( fp_got ); - } else { - printf("Could not open file: check_McIlwain_L_07.got\\n"); - } - - fflush(stdout); - fail_unless( Passed, "Lgm_McIlwain_L(): Regression test failed. Compare 'expected' and 'got' files: check_McIlwain_L_07.expected check_McIlwain_L_07.got\n" ); - - - return; -} -END_TEST - -START_TEST(test_MCILWAIN_08) { - - int Passed = FALSE; - long int Date; - double L, I, Bm, M, UTC; - double L_expected=-9e99, I_expected=-9e99, Bm_expected=-9e99, M_expected=-9e99; - Lgm_Vector u, v; - FILE *fp_expected; - FILE *fp_got; - - if ( (fp_expected = fopen( "check_McIlwain_L_08.expected", "r" )) != NULL ) { - - fscanf( fp_expected, "%lf", &L_expected ); - fscanf( fp_expected, "%lf", &I_expected ); - fscanf( fp_expected, "%lf", &Bm_expected ); - fscanf( fp_expected, "%lf", &M_expected ); - fclose( fp_expected ); - } else { - printf("Lgm_McIlwain_L(): Cant open file: check_McIlwain_L_08.expected\n" ); - } - - - Date = 20101012; UTC = 0.0; - Lgm_Set_Coord_Transforms( Date, UTC, mInfo->c ); - u.x = -4.2; u.y = 1.0; u.z = 1.0; - Lgm_Convert_Coords( &u, &v, SM_TO_GSM, mInfo->c ); - Lgm_MagModelInfo_Set_MagModel( LGM_IGRF, LGM_EXTMODEL_T89, mInfo ); - mInfo->Kp = 4.; - L = Lgm_McIlwain_L( Date, UTC, &v, 90.0, 0, &I, &Bm, &M, mInfo ); - - if ( (fabs( L-L_expected ) < 1e-7) && (fabs( I-I_expected ) < 1e-7) && (fabs( Bm-Bm_expected ) < 1e-7) && (fabs( M-M_expected ) < 1e-7) ) Passed = TRUE; - if ( !Passed ){ - - printf("\nTest 08, Lgm_McIlwain_L(): %15s %15s %15s %15s\n", " L ", " I ", " Bm ", " M "); - printf(" Expected: %.15g %.15g %.15g %.15g\n", L_expected, I_expected, Bm_expected, M_expected ); - printf(" Got: %.15g %.15g %.15g %.15g\n\n\n", L, I, Bm, M); - } - - if ( (fp_got = fopen( "check_McIlwain_L_08.got", "w" )) != NULL ) { - fprintf( fp_got, "%.15lf\n", L ); - fprintf( fp_got, "%.15lf\n", I ); - fprintf( fp_got, "%.15lf\n", Bm ); - fprintf( fp_got, "%.15lf\n", M ); - fclose( fp_got ); - } else { - printf("Could not open file: check_McIlwain_L_08.got\\n"); - } - - fflush(stdout); - fail_unless( Passed, "Lgm_McIlwain_L(): Regression test failed. Compare 'expected' and 'got' files: check_McIlwain_L_08.expected check_McIlwain_L_08.got\n" ); - - - return; -} -END_TEST Suite *McIlwain_L_suite(void) { @@ -461,10 +238,6 @@ Suite *McIlwain_L_suite(void) { tcase_add_test(tc_McIlwain_L, test_MCILWAIN_02); tcase_add_test(tc_McIlwain_L, test_MCILWAIN_03); tcase_add_test(tc_McIlwain_L, test_MCILWAIN_04); - tcase_add_test(tc_McIlwain_L, test_MCILWAIN_05); - tcase_add_test(tc_McIlwain_L, test_MCILWAIN_06); - tcase_add_test(tc_McIlwain_L, test_MCILWAIN_07); - tcase_add_test(tc_McIlwain_L, test_MCILWAIN_08); suite_add_tcase(s, tc_McIlwain_L); diff --git a/tests/check_McIlwain_L_02.expected b/tests/check_McIlwain_L_02.expected index 4a8e62feb..2def96982 100644 --- a/tests/check_McIlwain_L_02.expected +++ b/tests/check_McIlwain_L_02.expected @@ -1,4 +1,4 @@ -11.532648523255647 -12.824945140769978 -117.957520237165028 -29966.885119594124262 +11.478302249864024 +12.699517512431820 +118.288469284019740 +29966.895576135077135 diff --git a/tests/check_McIlwain_L_03.expected b/tests/check_McIlwain_L_03.expected index 5f918a82c..4f141e019 100644 --- a/tests/check_McIlwain_L_03.expected +++ b/tests/check_McIlwain_L_03.expected @@ -1,4 +1,4 @@ -3.176198757835458 -1.325580566009421 -1698.989634857761757 -30006.433375600576255 +3.166194330105079 +1.311446415884663 +1706.997141369585506 +30006.437989506655867 diff --git a/tests/check_McIlwain_L_04.expected b/tests/check_McIlwain_L_04.expected index be9edd490..2ffcb1ef2 100644 --- a/tests/check_McIlwain_L_04.expected +++ b/tests/check_McIlwain_L_04.expected @@ -1,4 +1,4 @@ -57.762457365712578 -139.866230008671238 -132.908184029350906 -29966.885119594124262 +57.489010375182040 +139.129903512580910 +133.262739493747830 +29966.895576135077135 diff --git a/tests/check_PolyRoots.c b/tests/check_PolyRoots.c index 4d6d8bd83..cab4b5208 100644 --- a/tests/check_PolyRoots.c +++ b/tests/check_PolyRoots.c @@ -143,7 +143,7 @@ START_TEST(test_PolyRoots_03) { double z2_r_expected, z2_i_expected; double z3_r_expected, z3_i_expected; double z4_r_expected, z4_i_expected; - double complex z1, z2, z3, z4, ztmp; + double complex z1, z2, z3, z4; double complex Residual1, Residual2, Residual3, Residual4; FILE *fp_expected; FILE *fp_got; @@ -163,21 +163,6 @@ START_TEST(test_PolyRoots_03) { b = -37.0; c = -1.0; d = 7.0; e = 60.0; nReal = Lgm_QuarticRoots( b, c, d, e, &z1, &z2, &z3, &z4 ); - /* - * The roots dshould be: - * 37.020721858115365 0.000000000000000 - * 1.233413878980077 0.000000000000000 - * -0.627067868547723 -0.959579313119009 - * -0.627067868547723 0.959579313119009 - * On some machines the last two get swapped. - * Do a swap on them if cimag(z4) < cimag(z3) - */ - if ( cimag(z4) < cimag(z3) ) { - ztmp = z4; - z4 = z3; - z3 = ztmp; - } - Residual1 = z1*z1*z1*z1 + b*z1*z1*z1 + c*z1*z1 + d*z1 + e; Residual2 = z2*z2*z2*z2 + b*z2*z2*z2 + c*z2*z2 + d*z2 + e; Residual3 = z3*z3*z3*z3 + b*z3*z3*z3 + c*z3*z3 + d*z3 + e; diff --git a/tests/check_libLanlGeoMag.c b/tests/check_libLanlGeoMag.c index a162460a4..cd4452034 100644 --- a/tests/check_libLanlGeoMag.c +++ b/tests/check_libLanlGeoMag.c @@ -1,9 +1,6 @@ #include #include "../libLanlGeoMag/Lgm/Lgm_CTrans.h" -#define TRUE 1 -#define FALSE 0 - /*BEGIN Leap seconds test case*/ Lgm_CTrans *c; @@ -26,7 +23,7 @@ START_TEST(test_IsLeapSecondDay_01) { printf("Testing to see if 19920630 is a leap second date (it should be)\n"); Result = Lgm_IsLeapSecondDay( 19920630, &sec_in_day, c ); - ck_assert_msg( ((Result == 1) && (sec_in_day == 86401)), "1992/6/30 should be a leap second day, with sec_in_day = 86401 (got %g)", sec_in_day); + fail_unless( ((Result == 1) && (sec_in_day == 86401)), "1992/6/30 should be a leap second day, with sec_in_day = 86401 (got %g)", sec_in_day); return; } @@ -39,7 +36,7 @@ START_TEST(test_IsLeapSecondDay_02) { printf("Testing to see if 19920629 is a leap second date (it should not be)\n"); Result = Lgm_IsLeapSecondDay( 19920629, &sec_in_day, c ); - ck_assert_msg( ((Result == 0) && (sec_in_day == 86400)), "1992/6/29 should be a leap second day, with sec_in_day = 86400 (got %g)", sec_in_day); + fail_unless( ((Result == 0) && (sec_in_day == 86400)), "1992/6/29 should be a leap second day, with sec_in_day = 86400 (got %g)", sec_in_day); return; } @@ -50,100 +47,32 @@ END_TEST START_TEST(test_GetLeapSeconds) { double n_leap = Lgm_GetLeapSeconds(2454984.0, c); printf("Check to see that number of leap seconds by 2009/6/1 is 34\n"); - ck_assert_msg( n_leap == 34.0, "Should be 34 leap seconds by 2009/6/1, not %f", n_leap); + fail_unless( n_leap == 34.0, "Should be 34 leap seconds by 2009/6/1, not %f", n_leap); return; } END_TEST // END Leap seconds test case +Suite *lgm_suite(void) { -START_TEST(test_VectorMagn) { - Lgm_Vector Utest; - int Passed; - double ans=3.7416573867739413, res; - - Utest.x = 1; Utest.y = 2; Utest.z = 3; - printf("Check that Lgm_Magnitude gives known answer: "); - - res = Lgm_Magnitude(&Utest); - Passed = (fabs(res-ans) <= 1e-12) ? TRUE : FALSE; - if (Passed) { - printf("Passed.\n"); - } else { - printf("Failed.\n"); - } - ck_assert(Passed); - return; -} -END_TEST - - -START_TEST(test_VectorNorm) { - Lgm_Vector Utest; - int Passed; - double ans=1.0, res; - - Utest.x = 1; Utest.y = 2; Utest.z = 3; - printf("Check that Lgm_NormalizeVector result has magnitude of 1: "); - - Lgm_NormalizeVector(&Utest); - res = Lgm_Magnitude(&Utest); - Passed = (fabs(res-ans) <= 1e-12) ? TRUE : FALSE; - if (Passed) { - printf("Passed.\n"); - } else { - printf("Failed.\n"); - } - ck_assert(Passed); - return; -} -END_TEST - - - + Suite *s = suite_create("LEAP_SECOND_TESTS"); -Suite *make_master_suite (void) { - Suite *s = suite_create("LGM Master Suite"); + TCase *tc_leapseconds = tcase_create("Leap seconds"); + tcase_add_checked_fixture(tc_leapseconds, leapsecond_setup, leapsecond_teardown); + tcase_add_test(tc_leapseconds, test_IsLeapSecondDay_01); + tcase_add_test(tc_leapseconds, test_IsLeapSecondDay_02); + tcase_add_test(tc_leapseconds, test_GetLeapSeconds); + suite_add_tcase(s, tc_leapseconds); - return s; -} - -Suite *lgm_ls_suite(void) { - - Suite *s = suite_create("LEAP_SECOND_TESTS"); - - TCase *tc_leapseconds = tcase_create("Leap seconds"); - tcase_add_checked_fixture(tc_leapseconds, leapsecond_setup, leapsecond_teardown); - tcase_add_test(tc_leapseconds, test_IsLeapSecondDay_01); - tcase_add_test(tc_leapseconds, test_IsLeapSecondDay_02); - tcase_add_test(tc_leapseconds, test_GetLeapSeconds); - suite_add_tcase(s, tc_leapseconds); - - return s; + return s; } -Suite *lgm_vec_suite(void) { - - Suite *s = suite_create("VECTOR_OPERATION_TESTS"); - - TCase *tc_vector = tcase_create("Test Lgm_Vector operations"); - tcase_add_test(tc_vector, test_VectorMagn); - tcase_add_test(tc_vector, test_VectorNorm); - suite_add_tcase(s, tc_vector); - - return s; - -} - - int main(void) { int number_failed; - Suite *s = make_master_suite(); + Suite *s = lgm_suite(); SRunner *sr = srunner_create(s); - srunner_add_suite (sr, lgm_ls_suite()); - srunner_add_suite (sr, lgm_vec_suite()); printf("\n\n\n======================================================\n"); printf("\n UNIT/REGRESSION TESTS \n");