This page was created by the IDL library routine `mk_html_help2`.

Last modified: Wed Sep 10 18:16:51 2025.

# Directory Listing of Routines

# projects/barrel/barrel_sp_v3.7

- GEO2MAG()
  Convert from geographic to geomagnetic coordinates
- BARREL_MAKE_MODEL_BKG
- BARREL_SELECTTIMES
- BARREL_SP_FITGRID1
- BARREL_SP_FITGRID2
- BARREL_SP_FITGRID3
- BARREL_SP_FITGRID4
- BARREL_SP_FOLD
- BARREL_SP_FOLD_M1
- BARREL_SP_FOLD_M2
- BARREL_SP_FOLD_M3
- BARREL_SP_FOLD_M4
- BARREL_SP_MAKE
- BARREL_SP_PICK_DATATIME
- BARREL_SP_READMODELSPEC
- BRL_REBIN
- EDGE_PRODUCTS
- GET_UNIQ

# Routine Descriptions

## BARREL_MAKE_MODEL_BKG

[Next Routine] [List of Routines]

     INPUT: energylist is a list of energies (keV)
            alt is altitude in km (20<alt<40)
            mlat is magnetic latitude in degrees (50<|mlat|<90)

     OUTPUT: returns a list of counts/s/kev corresponding to energylist
             returns -1 for input out of range

     METHOD: based on an empirical model derived from previous flights
             model is ok between 20 and 7000 keV
             background is primarily two power law components
                these turn over at low energy
                the 511 line contributes several features
             prevent underflows by avoiding exp(-huge number)

     CALLS: none

     EXAMPLE: result = brl_makebkgd([10,20,50,100],63,33.2)
                calculates bkgd differential count rate at the
                4 specified energies for a detector at mag lat
                63 degrees and altitude 33.2 km.

     FUTURE WORK:
            needs to be compared with BARREL test flights

     REVISION HISTORY:
            works, tested mm/18 Dec 2012

(See projects/barrel/barrel_sp_v3.7/barrel_make_model_bkg.pro)

## BARREL_SELECTTIMES

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_selecttimes.pro
    DESCRIPTION: use mouse to select a time interval from a lightcurve
    already plotted

    REQUIRED INPUTS:
    x,y     x and y values of data plotted (lightcurve)

    OPTIONAL INPUTS:
    color   color code for overplotting selected data

    OUTPUTS:
    subset       locations of selected data in the array
    subsetsize   length of array "subset"

    CALLS:  cursor

    NOTES:

    STATUS: ok

    TO BE ADDED:
    might possibly add a mouse-free option later

    REVISION HISTORY:
    Version 3.0 DMS 9/9/13
      change since version 2.9: removed xplot start and end (not used)

(See projects/barrel/barrel_sp_v3.7/barrel_selecttimes.pro)

## BARREL_SP_FITGRID1

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fitgrid1.pro
    DESCRIPTION: BARREL low-level spectral folding routine, method 1
                 (analytic spectral model, single drm)

    REQUIRED INPUTS:
    subspec   background subtracted count spectrum, cts/keV
    subspecerr    its error bars
    model     spectral model of electron spectrum (default is exponential)
              1 = exponential
              2 = monoenergetic
    drm       response matrix for correct payload altitude and chosen PID
              of electrons
    phmean    energy bin centers for the photons dimension
    phwidth   energy bin widths for the photons dimension
    usebins   which energy channels to use in minimizing chisquare
    startpar  Starting value of spectral parameter
    startnorm Starting value of spectral normalization
    points    Number of points on each side of starting values to test
    scaling   Range around the starting values to test -- for example,
              points=2 and scaling=1.5 means that the values tested are
              x/1.5, x/1.25, x, x*1.25, x*1.5

    OPTIONAL INPUTS:
    none

    OUTPUTS:
    bestpar   best-fit value of the spectral parameter
    bestnorm   best-fit value of the normalization parameter
    bestparn   array location of bestpar
    bestnormn  array location of bestnorm
    modvals    values of the best-fit function at the data bin centers
    chiarray   array of chi-square values
    bestchi    lowest chi-square value
    pararray   array of spectral parameter values
    normarray  array of normalization parameter values

    CALLS:  None.

    STATUS: Passed early test on artificial data

    TO BE ADDED: N/A

    REVISION HISTORY:
    Version 1.0 DMS 6/23/12 as barrel_fitgrid
    Version 2.0 DMS 7/18/12 added "usebins" -- functionality was missing
                            before -- renamed "bestvals" to "modvals"
    Version 2.4 DMS 8/26/12 added support for monoenergetic spectrum
                            removed redundant routine ID in "message"
                   11/12/13 insist on only one value of bestparn, etc.
    Version 3.4 DMS 4/17/14 fixed modvals and foldvals to be /chan
                            instead of /keV for model=2 (monoenergetic)

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fitgrid1.pro)

## BARREL_SP_FITGRID2

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fitgrid2.pro
    DESCRIPTION: BARREL low-level spectral folding routine, method 2
                 (single model file, single drm)

    REQUIRED INPUTS:
    subspec   background subtracted count spectrum, cts/keV
    subspecerr    its error bars
    model     spectral model of electron spectrum (default is exponential)
              1 = exponential
              2 = monoenergetic
    drm       response matrix for correct payload altitude and chosen PID
              of electrons
    phmean    energy bin centers for the photons dimension
    phwidth   energy bin widths for the photons dimension
    usebins   which energy channels to use in minimizing chisquare
    startpar  Starting value of spectral parameter
    startnorm Starting value of spectral normalization
    points    Number of points on each side of starting values to test
    scaling   Range around the starting values to test -- for example,
              points=2 and scaling=1.5 means that the values tested are
              x/1.5, x/1.25, x, x*1.25, x*1.5

    OPTIONAL INPUTS:
    none

    OUTPUTS:
    bestpar   best-fit value of the spectral parameter
    bestnorm   best-fit value of the normalization parameter
    bestparn   array location of bestpar
    bestnormn  array location of bestnorm
    modvals    values of the best-fit function at the data bin centers
    chiarray   array of chi-square values
    bestchi    lowest chi-square value
    pararray   array of spectral parameter values
    normarray  array of normalization parameter values

    CALLS:  None.

    STATUS: Passed early test on artificial data

    TO BE ADDED: N/A

    REVISION HISTORY:
    Version 1.0 DMS 7/24/12 derived from barrel_fitgrid1
                   11/12/13 insist on only one value of bestparn, etc.

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fitgrid2.pro)

## BARREL_SP_FITGRID3

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fitgrid3.pro
    DESCRIPTION: BARREL low-level spectral folding routine, method 3
                 ( two file-based spectral shapes, single drm)

    REQUIRED INPUTS:
    subspec   background subtracted count spectrum, cts/keV
    subspecerr    its error bars
    modelspec1    first spectral component (at all energies)
    modelspec2    second spectral component
    drm       response matrix for correct payload altitude and chosen PID
              of electrons
    phmean    energy bin centers for the photons dimension
    phwidth   energy bin widths for the photons dimension
    usebins   which energy channels to use in minimizing chisquare
    startnorm1    Starting value of normalization of 1st component
    startnorm2    Starting value of normalization of 2nd component
    points    Number of points on each side of starting values to test
    scaling   Range around the starting values to test -- for example,
              points=2 and scaling=1.5 means that the values tested are
              x/1.5, x/1.25, x, x*1.25, x*1.5

    OPTIONAL INPUTS:
    none

    OUTPUTS:
    bestnorm1  best-fit value of the first normalization
    bestnorm2  best-fit value of the second normalization
    bestnorm1n   array location of bestnorm1
    bestnorm2n   array location of bestnorm2
    modvals1          values of the fit function at the centers of the energy bins (first component)
    modvals2          values of the fit function at the centers of the energy bins (second component)
    chiarray   array of chi-square values
    bestchi    lowest chi-square value
    norm1array   array of first normalization parameter values
    norm2array   array of second normalization parameter values

    CALLS:  None.

    STATUS: Passed early test on artificial data

    TO BE ADDED: N/A

    REVISION HISTORY:
    First version with release 2.3, 8/26/12
                   11/12/13 insist on only one value of bestparn, etc.

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fitgrid3.pro)

## BARREL_SP_FITGRID4

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fitgrid4.pro
    DESCRIPTION: BARREL low-level spectral folding routine for method 4
       (analytic spectral function, dual DRMs)

    REQUIRED INPUTS:
    subspec   background subtracted count spectrum, cts/keV
    subspecerr    its error bars
    model     spectral model of electron spectrum (default is exponential)
              1 = exponential
              2 = monoenergetic
    drm       response matrix for correct payload altitude and chosen PID
              of electrons
    drm2      second response matrix; interpolation between these two is
              the last fit parameter
    phmean    energy bin centers for the photons dimension
    phwidth   energy bin widths for the photons dimension
    usebins   which energy channels to use in minimizing chisquare
    startpar  Starting value of spectral parameter
    startnorm Starting value of spectral normalization
    startdrm  Starting value of drm parameter
    points    Number of points on each side of starting values to test
    scaling   Range around the starting values to test -- for example,
                 points=2 and scaling=1.5 means that the values tested are
                 x/1.5, x/1.25, x, x*1.25, x*1.5
                 scaling[0]=norm, scaling[1]=spectral parameter,
                 scaling[2]=drm and works differently (direct value
                 rather than fractional)
    OPTIONAL INPUTS:
    none

    OUTPUTS:
    bestpar   best-fit value of the spectral parameter
    bestnorm   best-fit value of the normalization parameter
    bestdrm    best-fit value of the drm interpolation
    bestparn   array location of bestpar
    bestnormn  array location of bestnorm
    bestdrmn   array location of bestdrm
    modvals   values of the best-fit function at the data bin centers
    chiarray   array of chi-square values
    bestchi    lowest chi-square value
    pararray   array of spectral parameter values
    normarray  array of normalization parameter values
    drmarray   array of drm parameter values

    CALLS:  None.

    STATUS: not yet tested

    TO BE ADDED: N/A

    REVISION HISTORY:
    Version 1.0 DMS 7/12/12 based on barrel_fitgrid2
    Version 2.0 DMS 7/18/12 added "usebins" -- functionality was missing
                            before -- renamed "bestvals" to "modvals"
                            "scaling" becomes an array instead of 3
                            variables with different names
    Version 2.1 DMS 7/24/12 Add code to omit unphysical drm scale regions
                   11/12/13 insist on only one value of bestparn, etc.

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fitgrid4.pro)

## BARREL_SP_FOLD

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fold.pro
    DESCRIPTION: BARREL top-level spectral folding routine

    REQUIRED INPUTS:
    ss        spectrum structure

    OPTIONAL INPUTS:
    method    1 = single-parameter spectrum, single drm, use "model"
              2 = single fixed (file input) spectrum, single drm
              3 = double fixed (file input) spectrum, single drm
              4 = single-parameter spectrum, dual drm, use "model"
              5 = single fixed (file input)) spectrum, dual drm
              6 = double fixed (file input)) spectrum, dual drm
    model     spectral model of electron spectrum (default is exponential)
              1 = exponential
              2 = monoenergetic
    fitrange  energy range to use for fitting (regardless of full range
              of ebins) (this is a vector [start,end]
    maxcycles Maximum number of times to try rescaling range for fit parameters
    quiet     Don't make graphs + screen output
    verbose   show some debugging info as fits go along
    modlfile        Filename for inputting a handmade model component
    secondmodlfile  Filename for inputting a second handmade model component
    bkg_renorm      match background to source > 3 MeV before subtracting
    systematic_error_frac    Fraction of bkg-subtracted value to be added
                             in quadrature with statistical errors.
                             Typical value might be 0.1 (10%)

    OUTPUTS (written into ss structure):
    params            best fit parameters
    param_ranges      ranges on best fit parameters (1 sigma) (2x2 array)
    chisquare         chi-square (not reduced)
    dof               degrees of freedom associated with chisquare
    modvals           values of the fit function at the centers of the energy bins

    CALLS:
    edge_products(), (imported from solarsoft), barrel_sp_fold_m1
    through barrel_sp_fold_m6

    NOTES:

    STATUS: Tested for methods 1&4 on artificial data.

    TO BE ADDED:
         Support for other spectral models
         Support for single + summed fixed spectra (from file), varying normalization

    REVISION HISTORY:
    Version 1.0 DMS 7/18/12 -- split out from barrel_folding as the new top layer
                    7/24/12 -- fixed minimum of plot to account for
                               possible values << 1 (fixed threshold for minimum
                               of plot changed to 1.d-6 instead of 0.5
                               when there are real values that are too low)
              2.3   8/19/12 -- added support for method 3
              2.5   1/5/13 --  rewrite to support new general
                               spectroscopy structure ss
              2.6   5/29/13 -- adding support for L2 MSPC files (already cts/keV)
              2.8   7/8/13  -- remove call to idl_screen_graphics()
              3.0   9/9/13  -- set ss.numparams here instead of upstream at barrel_sp_make()
              3.2   10/29/13 - Print total, background, and net count
                               rates just before proceeding to fit
                    11/12/13 - plot data before fitting in case fit crashes
                    11/12/13 - bkg_renorm defaults to zero, not 1.
              3.4   4/17/14  - Report counts & electron flux for best fit.
                               Keep track of best-fit model in electron
                               space and save it and print the total.
                               Fixed bug that would use bkg_renorm
                               regardless of setting.
                               Make explicit that method 4 isn't ready yet.
              3.5   8/12/14    Option for adding a fraction of the
                               background-subtracted spectrum as error
                               This keeps very small error bars at low
                               energies from over-dominating the fit, and
                               represents, e.g., systematic uncertainties
                               in the response matrix.
              3.6 2/12/15      pass altitude to _m1 for initial param. guess
              9/23/15          Change x-axes for plots to [10,1000] always
                               broadened range of default ratio plot
                               residuals=2 counts only pts in fit range.

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fold.pro)

## BARREL_SP_FOLD_M1

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fold_m1.pro
    DESCRIPTION: BARREL mid-level spectral folding routine
                 method1 = single-parameter analytic spectrum, single drm

    REQUIRED INPUTS:
    subspec   background subtracted count spectrum
    subspecerr    its error bars
    model     spectral model of electron spectrum (default is exponential)
              1 = exponential
              2 = monoenergetic
    drm       response matrix for correct payload altitude and chosen PID
              of electrons
    phmean    energy channel centers (should have length = length of spectrum)
              -- this is for the photons dimension
    phwidth   energy channel widths (should have length = length of spectrum)
              -- this is for the photons dimension
    ctwidth   energy channel widths (should have length = length of spectrum)
              -- this is for the counts dimension
    ctmean    energy channel centers (should have length = length of spectrum)
              -- this is for the counts dimension
    usebins   subset of energy channels (count space) to actually use for fitting
    maxcycles Maximum number of times to try rescaling range for fit parameters

    OPTIONAL INPUTS:
    quiet     Don't make graphs + screen output
    verbose   show some debugging info as fits go along

    OUTPUTS:
    params            best fit parameters
    param_ranges      ranges on best fit parameters (1 sigma) (2x2 array)
    modvals           values of the fit function at the centers of the energy bins
    chisquare         chi-square (not reduced)
    dof               degrees of freedom associated with chisquare

    CALLS:
    barrel_sp_fitgrid1.pro

    STATUS: Tested with artificial data, 7/20/12

    TO BE ADDED:
         Support for other spectral models

    REVISION HISTORY:
    Version 1.0 DMS 7/18/12 -- split out from barrel_folding as new middle layer;
                               fixed "dof" to use "usebins" (at the same
                               time as fixing "fitgrid1" to use "usebins")
    Errors fixed 7/20/12 -- definition of "tryspec" didn't include
                           multiplication by "phwidth", meaning lousy
                           starting point for fits -- which converged anyway.
    Version 2.3 DMS ;8/26/12 -- fixed logical error in rescaling
                          algorithm in search for chisquare+1 contour.
                          Removed redundant routine identifier from "message"
    Version 2.4 DMS 8/26/12 -- added support for model 2 (monoenergetic)
    Version 3.4 DMS 4/17/14 -- save elecmodel for best fit e- spectrum
    Version 3.6 DMS 2/12/15    Use dynamic generation of first-guess
                               parameters based on true altitude

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fold_m1.pro)

## BARREL_SP_FOLD_M2

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fold_m2.pro
    DESCRIPTION: BARREL mid-level spectral folding routine
                 method2 = single-parameter file-based spectrum, single drm

    REQUIRED INPUTS:
    subspec   background subtracted count spectrum
    subspecerr    its error bars
    modlfile  Input model spectrum.  Required format is
              starting energy boundary, ending energy boundary, flux
              it will be interpolated to phebins if necessary.  Comment
              lines beginning with characters not = '0123456789.-' are
              allowed at the start.
    drm       response matrix for correct payload altitude and chosen PID
              of electrons
    phebins   energy channel boundaries (length = length of spectrum + 1)
    phmean    energy channel centers (should have length = length of spectrum)
              -- this is for the photons dimension
    phwidth   energy channel widths (should have length = length of spectrum)
              -- this is for the photons dimension
    ctwidth   energy channel widths (should have length = length of spectrum)
              -- this is for the counts dimension
    usebins   subset of energy channels (count space) to actually use for fitting
    maxcycles Maximum number of times to try rescaling range for fit parameters

    OPTIONAL INPUTS:
    quiet     Don't make graphs + screen output
    verbose   show some debugging info as fits go along

    OUTPUTS:
    params            best fit parameters (only one in this case)
    param_ranges      range on best fit parameter (1 sigma)
    modvals           values of the fit function at the centers of the energy bins
    chisquare         chi-square (not reduced)
    dof               degrees of freedom associated with chisquare

    CALLS:
    barrel_sp_readmodelspec, barrel_sp_fitgrid2

    STATUS:

    TO BE ADDED:

    REVISION HISTORY:
    Version 1.0 DMS 7/24/12 -- split out from barrel_folding as new middle layer;
                               fixed "dof" to use "usebins" (at the same
                               time as fixing "fitgrid1" to use "usebins")
    Version 2.3 DMS ;8/26/12 -- Removed redundant routine identifier from "message"
    Version 3.4 DMS 4/17/14 -- save elecmodel for best fit e- spectrum

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fold_m2.pro)

## BARREL_SP_FOLD_M3

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fold_m3.pro
    DESCRIPTION: BARREL mid-level spectral folding routine
                 method3 = two file-based spectral shapes, single drm

    REQUIRED INPUTS:
    subspec   background subtracted count spectrum
    subspecerr    its error bars
    modlfile Input model spectrum.  Required format is
              starting energy boundary, ending energy boundary, flux
              it will be interpolated to phebins if necessary.  Comment
              lines beginning with characters not = '0123456789.-' are
              allowed at the start.
    secondmodlfile Second input model spectrum.
    drm       response matrix for correct payload altitude and chosen PID
              of electrons
    phebins   energy channel boundaries (length = length of spectrum + 1)
    phmean    energy channel centers (should have length = length of spectrum)
              -- this is for the photons dimension
    phwidth   energy channel widths (should have length = length of spectrum)
              -- this is for the photons dimension
    ctwidth   energy channel widths (should have length = length of spectrum)
              -- this is for the counts dimension
    usebins   subset of energy channels (count space) to actually use for fitting
    maxcycles Maximum number of times to try rescaling range for fit parameters

    OPTIONAL INPUTS:
    quiet     Don't make graphs + screen output
    verbose   show some debugging info as fits go along

    OUTPUTS:
    params            best fit parameters
    param_ranges      ranges on best fit parameters (1 sigma) (2x2 array)
    modvals           values of the fit function at the centers of the energy bins (first component)
    secondmodvals     values of the fit function at the centers of the energy bins (second component)
    chisquare         chi-square (not reduced)
    dof               degrees of freedom associated with chisquare

    CALLS:
    barrel_sp_fitgrid3.pro

    STATUS:

    TO BE ADDED:

    REVISION HISTORY:
    Version 1.0 DMS 8/18/12
    Version 3.4 DMS 4/17/14 -- save elecmodel for best fit e- spectrum

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fold_m3.pro)

## BARREL_SP_FOLD_M4

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_fold_m4.pro
    DESCRIPTION: BARREL mid-level spectral folding routine
                 method4 = analytical spectral model + dual DRMs

    REQUIRED INPUTS:
    subspec   background subtracted count spectrum
    subspecerr    its error bars
    model     spectral model of electron spectrum (default is exponential)
              1 = exponential
              2 = monoenergetic
    drm       response matrix for correct payload altitude and chosen PID
              of electrons
    drm2      second response matrix (will find allowed interpolated
              range between these two)
    phmean    energy channel centers (should have length = length of spectrum)
              -- this is for the photons dimension
    phwidth   energy channel widths (should have length = length of spectrum)
              -- this is for the photons dimension
    ctwidth   energy channel widths (should have length = length of spectrum)
              -- this is for the counts dimension
    usebins   subset of energy channels (count space) to actually use for fitting
    maxcycles Maximum number of times to try rescaling range for fit parameters

    OPTIONAL INPUTS:
    quiet     Don't make graphs + screen output
    verbose   show some debugging info as fits go along

    OUTPUTS:
    params            best fit parameters
    param_ranges      ranges on best fit parameters (1 sigma) (2x2 array)
    modvals           values of the fit function at the centers of the energy bins
    chisquare         chi-square (not reduced)
    dof               degrees of freedom associated with chisquare

    CALLS:
    barrel_sp_fitgrid4.pro

    STATUS:

    TO BE ADDED:
         Support for other spectral models
         Reasonable formula to guess e-folding or mono-E from count spectrum

    REVISION HISTORY:
    Version 1.0 DMS 7/18/12 -- split out from barrel_folding as new middle layer;
                               fixed "dof" to use "usebins" (at the same
                               time as fixing "fitgrid1" to use "usebins")
    Errors fixed 7/20/12 -- definition of "tryspec" didn't include
                           multiplication by "phwidth", meaning lousy
                           starting point for fits -- which converged anyway.
    Version 2.3 DMS ;8/26/12 -- fixed logical error in rescaling
                                algorithm in search for chisquare+1 contour.
                                Removed redundant routine identifier from "message"
    Version 2.4 DMS 8/26/12 -- added support for model 2 (monoenergetic)
    Version 3.4 DMS 4/17/14 -- save elecmodel for best fit e- spectrum

(See projects/barrel/barrel_sp_v3.7/barrel_sp_fold_m4.pro)

## BARREL_SP_MAKE

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_make.pro (function)
    DESCRIPTION: Creates spectroscopy data structure

    REQUIRED INPUTS: none

    OPTIONAL INPUTS:
    numsrc           # of source spectrum time intervals (default 1)
    numbkg           # of background spectrum time intervals (default 1)
    slow             slow (256-channel) spectra versus default medium

    OUTPUTS:
    returns the spectroscopy system structure that is passed to all
    subsequent spectroscopy routines.  The structure content will vary
    with software version.

    CALLS:
    barrel_make_standard_energies(),barrel_make_standard_electron_energies()

    NOTES:

    STATUS: up to date

    TO BE ADDED: only in response to changes in other routines

    REVISION HISTORY:
    Version 3.0 DMS 9/9/13
     revisions from 2.9:  add size options for slow spectra
                          postpone numparams until fitting routine; leave
                              room for a large number (10)
     3.4       4/17/14    Add space for best fit model in e- space

(See projects/barrel/barrel_sp_v3.7/barrel_sp_make.pro)

## BARREL_SP_PICK_DATATIME

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_pick_datatime.pro

    DESCRIPTION: Pick start and stop times for spectral accumulation and
    background

    REQUIRED INPUTS:
    ss                spectrum structure
    startdatetime     start time for plot from which we will pick source
                      and background times, format yyyy-mm-dd/hh:mm:ss
    duration          duration in hours to look, starting at startdatetime
    payload           payload ID, with format, e.g., '1G'
    bkgmethod         1=select bkg intervals from data stream
                      2=use bkg model from U. of Washington

    OPTIONAL INPUTS:
    lcband            which FSPC band to plot during selection (default 1)
    uselog            plot FSPC data on a log scale (default 0)
    level             data CDF level (default 'l2')
    version           data CDF version for barrel_load_data.  If not
                      specified, use that routine's default
    starttimes,endtimes,startbkg,endbkg:
       start and end times (string format or unix epoch) for source
       and background intervals (if not to be selected graphically)

    medticks,slowticks   Show vertical dotted lines at the start and
                         and of medium, slow spectra (for use only
                         when zoomed in to small times!

    OUTPUTS: No direct outputs, but the spectrum structure ss gets
    updated with trange and bkgtrange (primary purpose of this routine),
    also: payload,askdate, askduration, bkgmethod

    CALLS: barrel_load_data, barrel_selecttimes

    NOTES:

    STATUS:

    TO BE ADDED:

    REVISION HISTORY:
    Version 3.0 DMS 9/9/13
       Most recent changes from v2.9:
       remove passing x start and stop values to barrel_selecttimes
    KY 8/28/13 'brl???_' -> 'brl' and '_LC' -> '_FSPC' (update tplot
       variable names)
    9/30/13 -- remove "dobkg"; whether background intervals are
       selected should automatically follow bkgmethod.
    10/1/13 -- put in option for already having specified the time ranges
               by hand. (start/end times/bkgs)
    10/25/13 -- add provision for start/end times entered by hand to be
               already in unix epoch (as from a prev. run)
    10/29/13 - Add plot of altitude to assist in background selection
    11/12/13 - Add option for vertical ticks for medium and slow spectra
    11/12/13 - Add default "no update" for reading FSPC data
    2/10/15 DMS - collect altitude using correct source time interval (average)
    3/5/15 DMS - cull out "NaNs" from altitude data before averaging
    8/20/15 DMS - fix bug wherein 3/5 fix only applied to
                  screen-selected, not predetermined time intervals.
                  This reorders operations somewhat
    4/5/16 DMS - fixed erroneous "numspec" to "numbkg" when looping to
                 set multiple background intervals by hand.

(See projects/barrel/barrel_sp_v3.7/barrel_sp_pick_datatime.pro)

## BARREL_SP_READMODELSPEC

[Previous Routine] [Next Routine] [List of Routines]

    NAME: barrel_sp_readmodelspec.pro
    DESCRIPTION: Spectral model file reader for barrel folding routines.
                 File format must be 3 columns, start-energy, end-energy,
                 flux per keV at center of the bin.

    REQUIRED INPUTS:
    fname     spectrum file name
    phebins   energy channel boundaries desired (may or may not match file)
    phmean    energy channel centers

    OPTIONAL INPUTS:
    none

    OUTPUTS:
    outspec           model spectrum in flux per keV at the values phmean

    CALLS:
    none

    STATUS:           Tested with artificial data, both with and without interpolation

    TO BE ADDED:      N/A

    REVISION HISTORY:
    Version 1.0 DMS 7/24/12
    Version 3.4 DMS 4/17/14:  The interpolation kills a single-bin
          (monoenergetic) flux or other narrow features.  Replace
          "interpol" with "hsi_rebinner" for rebinning to our bins.
          Warning: our bins are broad so we will lose some information
          about where within the bin the flux actually is.  Use
          method=1, model=2 (precise monoenergetic) for mono. models
          instead.

(See projects/barrel/barrel_sp_v3.7/barrel_sp_readmodelspec.pro)

## BRL_REBIN

[Previous Routine] [Next Routine] [List of Routines]

     INPUT: oldBins is a list of bin edges. It contains n>=2 unique
                elements sorted in ascending order
            newBins is a list of bin edges. It contains m>=2 unique
                elements sorted in ascending order
            oldVals is a list of n-1 values associated to
                oldBins, the values to interpolate. That is,
                oldVals[i] is associated with the bin having edges
                (oldBins[i], oldBins[i+1]).
            flux set means oldVals are counts/binWidth, not counts

     OUTPUT: returns a list of m-1 interpolated values associated to
                newBins

     METHOD: traverse both bin lists once. For each old bin
                there are 4 possibilities:
                   a) old bin precedes current new bin
                   b) new bin precedes the current old bin
                   c) old bin overlaps new bin, extends beyond
                   d) old bin overlaps new bin, does not extend beyond
     CALLS: none

     NOTES: 1. algorithm is simple linear interpolation.
            2. The interpolated vector might contain less
                information than the input vector. Exchanging oldBins
                and newBins is not an inverse function for brl_rebin().
            3. Difference between FLUX=0 and FLUX=1: suppose
                the old and new binning schemes have the same
                total range. Then FLUX=0 preserves the sum of
                oldVals, and would be used when oldVals represents
                counts in each bin, whereas FLUX=1 preserves the dot
                product of oldVals and the (n-1 length) vector of
                differences between successive oldBin entries---used
                when oldVals has counts divided by bin width.

     WARNING: since this might be called repeatedly with only
                oldVals changing, error-checking is minimal. The
                calling routine is responsible for error-checking.

     REVISION HISTORY:
            works, not much testing mm/Jul 2012
    	 22Oct2012: corrected normalization for flux eq 0
            01Jan2013: calculates array lengths n&m automatically (DMS)

(See projects/barrel/barrel_sp_v3.7/brl_rebin.pro)

## EDGE_PRODUCTS

[Previous Routine] [Next Routine] [List of Routines]

     Name: edge_products

     Purpose: From a vector of contiguous channel boundaries return the
       commonly used quantities for plotting and scaling.

     Category:
       GEN, SPECTRA

     Input: Edges -if 1d, contiguous channel boundaries, n+1 values for n channels
                   if 2d, 2xn, [lo(i),hi(i)], etc., assumed contiguous for
         calculating edges_1

     Output:
       Mean - arithmetic mean of boundaries
           Gmean - geometric mean
       width - absolute difference between upper and lower edges
       edges_2 - 2xn array of edges [lo(i), hi(i)], etc.
           edges_1 - array of n+1 edges of n contiguous channels

           Keyword Input
           EPSILON - If the absolute relative difference is less than epsilon
           then two numbers are considered to be equal and a new bin is not required under
       the contiguous requirement.  If epsilon isn't passed but CONTIGOUS is set it
           attempts to construct an epsilon based on the average relative difference between
           adjacent bins, it takes that value and multiplies it by 1e-5 and limits that to
           1e-6
       CONTIGUOUS - force all edges to be contiguous, including edges_1

     Mod. History:
     ras, 21-oct-93
     8-dec-2001, richard.schwartz@gsfc.nasa.gov, added CONTIGUOUS
     added protection against degenerate entry of single value for edges,
     clearly edges_2 and width have no meaning, but are set to edges and 0.0 respectively
     25-aug-2006, ras, added epsilon and default epsilon as test
           to differentiate real numbers. If the absolute relative difference is less than epsilon
           then two numbers are considered to be equal and a new bin is not required under
       the contiguous requirement

(See projects/barrel/barrel_sp_v3.7/edge_products.pro)

## GEO2MAG()

[Previous Routine] [Next Routine] [List of Routines]

     NAME:
           GEO2MAG()

     PURPOSE:
           Convert from geographic to geomagnetic coordinates
     EXPLANATION:
           Converts from GEOGRAPHIC (latitude,longitude) to GEOMAGNETIC (latitude,
           longitude).   (Altitude remains the same)

           Latitudes and longitudes are expressed in degrees.

     CALLING SEQUENCE:
           mcoord=geo2mag(gcoord)

     INPUT:
           gcoord = a 2-element array of geographic [latitude,longitude], or an
                    array [2,n] of n such coordinates.

     KEYWORD INPUTS:
           None

     OUTPUT:
           a 2-element array of magnetic [latitude,longitude], or an array [2,n]
             of n such coordinates

     COMMON BLOCKS:
           None

     EXAMPLES:
           geographic coordinates of magnetic south pole

           IDL> mcoord=geo2mag([79.3,288.59])
           IDL> print,mcoord
           89.999992      -173.02325

     MODIFICATION HISTORY:
           Written by Pascal Saint-Hilaire (Saint-Hilaire@astro.phys.ethz.ch),
                May 2002
           Changed the name to avoid conflicts, jmm, 2017-12-13, no other
           changes from the SSW version

(See projects/barrel/barrel_sp_v3.7/barrel_geo2mag.pro)

## GET_UNIQ

[Previous Routine] [List of Routines]

     Project     : HESSI

     Name        : get_uniq

     Purpose     : return unique elements of an array

     Category    : utility
    ;
     Syntax      : IDL> out=get_uniq(in)

     Inputs      : IN = array to search

     Outputs     : OUT = unique elements

     Optional Out: SORDER = sorting index

     Keywords    : NO_CASE: case insensitive ordering on strings
                   COUNT: # of uniq values
                                   EPSILON:  positive number ge 0, for gt 0 the difference between
                                   two consecutive numbers must be gt epsilon for them to be unique.

     History     : Written 20 Sept 1999, D. Zarro, SM&A/GSFC
                                   25-Aug-2006, richard.schwartz@gsfc.nasa.gov;  added an epsilon tolerance
                                   for determining floats to be the same value

     Contact     : dzarro@solar.stanford.edu

(See projects/barrel/barrel_sp_v3.7/get_uniq.pro)