# importing the needed classes and functions from HAWCNest import HAWCNest from HAWCNest import load from HAWCNest import GetService_MainLoop # loading shared libraries that might be needed for processing load("libhawcnest") load("libexample-hawcnest") # This is nearly identical to the C++ interface, except it uses python # syntax nest = HAWCNest() # adding and configuring services nest.Service("STDRandomNumberService", "rand")(("Seed", 12345)) nest.Service("DBCalibrationService", "calib")( ("server", "mildb.umd.edu")("uname", "milagro")("password", "topsecret")) nest.Service("ExampleSource", "source")(("input", "myinputfile.dat")("maxevents", 20)) nest.Service("CalibrationModule", "calibmodule") nest.Service("ReconstructionModule_COM", "reco_com") nest.Service("ReconstructionModule_Gauss", "reco_gauss") nest.Service("PrintingModule", "print") nest.Service("SequentialMainLoop", "mainloop")(("source", "source")( "modulechain", ["print", "calibmodule", "reco_com", "reco_gauss", "print", "mymodule"]), ) nest.Configure() main = GetService_MainLoop("mainloop") loop.Execute() nest.Finish()
"""Test access to the astro-service project via its python bindings. .. codeauthor:: Segev BenZvi """ __version__ = "$Id" try: from hawc import hawcnest, data_structures, astro_service from hawc.data_structures import * from hawc.hawcnest import HAWCUnits as U from HAWCNest import HAWCNest except ImportError as e: print(e) raise SystemExit nest = HAWCNest() nest.Service("StdAstroService", "astroX") nest.Configure() astroX = astro_service.GetService("astroX") # Define locations and times to be used in astronomical transformations loc = LatLonAlt(float(DegMinSec(18 * U.deg, 59 * U.arcmin, 41.63 * U.arcsec)), -float(DegMinSec(97 * U.deg, 18 * U.arcmin, 27.39 * U.arcsec)), 4096 * U.meter) utc0 = UTCDateTime(2007, 10, 4, 3, 3, 3) mjd0 = ModifiedJulianDate(utc0) utc1 = UTCDateTime(2010, 4, 27, 19, 19, 19) mjd1 = ModifiedJulianDate(utc1)
parser.add_argument("-a", "--xmin", dest="a", type=float, default=1., help="Minimum power law range (a > 0).") parser.add_argument("-b", "--xmax", dest="b", type=float, default=1e2, help="Maximum power law range (0 < a <= b).") args = parser.parse_args() # Set up the HAWCNest framework and RNG service nest = HAWCNest() nest.Service("StdRNGService", "rng", seed=args.seed) nest.Configure() rng = rng_service.GetService("rng") x0, x1, A, idx = [args.a, args.b, 1., args.idx1] p1 = PowerLaw(x0, x1, A, x0, idx) p2 = PowerLaw(x0, x1, A, x0, args.idx2) x = [] wt = [] for i in range(args.size[0]): u = rng.PowerLaw(p1.spectral_index(x0), p1.xmin, p1.xmax)
#!/usr/bin/env python """Test the interface to the RNG service; just run and make sure no exceptions are thrown. .. codeauthor:: Segev BenZvi """ __version__ = "$Id" from hawc import hawcnest, data_structures, rng_service from HAWCNest import HAWCNest nest = HAWCNest() nest.Service("StdRNGService", "rng1", seed=-1) nest.Service("StdRNGService", "rng2", seed=0) nest.Service("StdRNGService", "rng3", seed=12345) nest.Configure()
def main(): usage = "%prog [options] [N = size of random data set]" parser = OptionParser(usage) parser.add_option("-s", "--seed", dest="seed", type=int, default=54112, help="Seed for random number generator") parser.add_option("", "--notest", dest="test", action="store_false", default=True, help="Skip integral tests") (opts, args) = parser.parse_args() if (len(args) != 1): parser.error("Wrong number of arguments!") nest = HAWCNest() nest.Service("StdRNGService", "rng", seed=opts.seed) nest.Configure() rng = rng_service.GetService("rng") x0, x1, idx1, idx2 = [1.0, 100.0, -2.0, -0.0] norm1 = 1.0 / PowerLaw(x0, x1, 1.0, x0, idx1).integrate(x0, x1) norm2 = 1.0 / PowerLaw(x0, x1, 1.0, x0, idx2).integrate(x0, x1) norm3 = 1.0 / BrokenPowerLaw(x0, x1, 1.0, x0, -1.0, 10.0, -2.0).integrate( x0, x1) norm4 = 1.0 / BrokenPowerLaw(x0, x1, 1.0, x0, -2.0, 10.0, -1.0).integrate( x0, x1) norm5 = 1.0/DoubleBrokenPowerLaw(x0,x1,1.0,x0,-1.4,4.5,0.4,34.2,-1.0). \ integrate(x0,x1) norm6 = 1.0 / CutoffPowerLaw(x0, x1, 1.0, x0, -1.0, 10.0).integrate(x0, x1) norm7 = 1.0 / PowerLaw(x0, x1, 1.0, x0, -4.7).integrate(x0, x1) p1 = PowerLaw(x0, x1, norm1, x0, idx1) p2 = PowerLaw(x0, x1, norm2, x0, idx2) p3 = BrokenPowerLaw(x0, x1, 10.0 * norm3, x0, -1.0, 10.0, -2.0) p4 = BrokenPowerLaw(x0, x1, 0.1 * norm4, x0, -2.0, 10.0, -1.0) p5 = DoubleBrokenPowerLaw(x0, x1, norm6, x0, -1.4, 4.5, 0.4, 34.2, -1.0) p6 = CutoffPowerLaw(x0, x1, norm5, x0, -1.0, 10.0) p7 = PowerLaw(x0, x1, norm7, x0, -4.7) p8 = LogParabola(x0, x1, 1.0, x0, -0.3, -0.7) # Test the various power laws if (opts.test): runIntTests() print "Sampling", args[0], ("point" if int(args[0]) == 1 else "points") p1sample = [] p2weight = [] p3weight = [] p4weight = [] p5sample = [] p6weight = [] p7weight = [] p8weight = [] p2keeps = [] for i in range(0, int(args[0])): val = p1.invert_integral(rng.Uniform()) p1sample.append(val) p2weight.append(p2.reweight(p1, val)) p3weight.append(p3.reweight(p1, val)) p4weight.append(p4.reweight(p1, val)) val2 = p5.invert_integral(rng.Uniform()) p5sample.append(val2) p6weight.append(p6.reweight(p5, val2)) p7weight.append(p7.reweight(p5, val2)) p8weight.append(p8.reweight(p5, val2)) if (rng.Uniform() < p2.prob_to_keep(p1, val)): p2keeps.append(val) # Get the power law points xplot = 10.0**N.linspace(P.log10(x0), P.log10(x1), 1000) y1plot = [] y2plot = [] y3plot = [] y4plot = [] y5plot = [] y6plot = [] y7plot = [] y8plot = [] for i in range(0, len(xplot)): y1plot.append(p1.evaluate(xplot[i]) / p1.integrate(x0, x1)) y2plot.append(p2.evaluate(xplot[i])) y3plot.append(p3.evaluate(xplot[i])) y4plot.append(p4.evaluate(xplot[i])) y5plot.append(p5.evaluate(xplot[i]) / p5.integrate(x0, x1)) y6plot.append(p6.evaluate(xplot[i])) y7plot.append(p7.evaluate(xplot[i])) y8plot.append(p8.evaluate(xplot[i])) # Make a log-log histogram of the random numbers gph1 = PrettyGraph(usetitle=True, xtitle="X", title="Reweighting power law with index " + str(idx1), ytitle="Counts", ylabeladjust=0.92, xlabeladjust=0.96, limits=[0.11, 0.97, 0.12, 0.95]) hc1 = HistogramConverter(data=p1sample, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="ro", label="Index -2", norm=True) hc2 = HistogramConverter(data=p1sample, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="bo", label="Index -1", norm=True, weights=p2weight) hc3 = HistogramConverter(data=p1sample, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="go", label="Broken -2 to -1", norm=True, weights=p3weight) hc4 = HistogramConverter(data=p1sample, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="yo", label="Broken -1 to -2", norm=True, weights=p4weight) fig, ax = gph1.make_graph() ax.set_xscale("log") ax.set_yscale("log") ax.set_autoscaley_on(False) ax.set_ylim([1.0e-4, 10.0]) hc1.make_plot(ax) hc2.make_plot(ax) hc3.make_plot(ax) hc4.make_plot(ax) ax.plot(xplot, y1plot, "r--") ax.plot(xplot, y2plot, "b--") ax.plot(xplot, y3plot, "g--") ax.plot(xplot, y4plot, "y--") handles, labels = ax.get_legend_handles_labels() leg = ax.legend(handles, labels, numpoints=1, bbox_to_anchor=[0.97, 0.95]) leg.get_frame().set_linewidth(0) # Now make it for the more complicated cases gph2 = PrettyGraph(usetitle=True, xtitle="X", title="Reweighting double broken power law", ytitle="Counts", ylabeladjust=0.92, xlabeladjust=0.96, limits=[0.11, 0.97, 0.12, 0.95]) hc5 = HistogramConverter(data=p5sample, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="ro", label="Double break sample", norm=True) hc6 = HistogramConverter(data=p5sample, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="bo", label="Cutoff", norm=True, weights=p6weight) hc7 = HistogramConverter(data=p5sample, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="go", label="Power law", norm=True, weights=p7weight) hc8 = HistogramConverter(data=p5sample, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="yo", label="Log parabola", norm=True, weights=p8weight) fig2, ax2 = gph2.make_graph() ax2.set_xscale("log") ax2.set_yscale("log") ax2.set_autoscaley_on(False) ax2.set_ylim([1.0e-9, 10.0]) hc5.make_plot(ax2) hc6.make_plot(ax2) hc7.make_plot(ax2) hc8.make_plot(ax2) ax2.plot(xplot, y5plot, "r--") ax2.plot(xplot, y6plot, "b--") ax2.plot(xplot, y7plot, "g--") ax2.plot(xplot, y8plot, "y--") handles2, labels2 = ax2.get_legend_handles_labels() leg2 = ax2.legend(handles2, labels2, numpoints=1, bbox_to_anchor=[0.45, 0.32]) leg2.get_frame().set_linewidth(0) gph3 = PrettyGraph(usetitle=True, xtitle="X", title="Resampling power law", ytitle="Counts", ylabeladjust=0.92, xlabeladjust=0.96, limits=[0.11, 0.97, 0.12, 0.95]) hc9 = HistogramConverter(data=p2keeps, lowedge=x0, highedge=x1, bincount=21, binstyle="log", opts="bo", label="Resampled", norm=True) fig3, ax3 = gph3.make_graph() ax3.set_xscale("log") ax3.set_yscale("log") ax3.set_autoscaley_on(False) ax3.set_ylim([1.0e-4, 1.0]) hc1.make_plot(ax3) hc9.make_plot(ax3) ax3.plot(xplot, y1plot, "r--") ax3.plot(xplot, y2plot, "b--") handles3, labels3 = ax3.get_legend_handles_labels() leg3 = ax3.legend(handles3, labels3, numpoints=1, bbox_to_anchor=[0.97, 0.95]) leg3.get_frame().set_linewidth(0) P.show()
parser.add_argument("-b", "--Emax", dest="Emax", type=float, default=200e3, help="Maximum energy [GeV].") args = parser.parse_args() # Set up spectrum parameters Emin = args.Emin * U.GeV Emax = args.Emax * U.GeV idx1 = args.idx1 idx2 = args.idx2 # Set up the HAWCNest framework and RNG service nest = HAWCNest() nest.Service("StdRNGService", "rng", seed=args.seed) nest.Service("GenericSpectrum", "injection", fluxNorm=1. / (U.GeV * U.meter2 * U.s * U.sr), energyNorm=Emin, spIndex=idx2, energyMin=Emin, energyMax=Emax) nest.Service("IsotropicCosmicRaySource", "crsource", sourceSpectrum="injection", particleType="Proton")
print("%6d -> %6d" % (bag["count"].value, bag["countx"].value)) return True return False def keeper(bag): """Stuff the 'count' and 'countx' elements in the bag into global arrays""" if "count" in bag and "countx" in bag: count.append(bag["count"].value) countx.append(bag["countx"].value) return True return False # Create source and module instances nest = HAWCNest() nest.Service(CountInserter, "countInserter", startCount=1, maxCount=20) # Module sequence: # 1) scale values by 4 using a named function # 2) filter out even-numbered results using an anonymous (lambda) function # 3) print results using a named function # 4) stuff results into global arrays to be checked at the end nest.Service(scaleBy3, "scaler") nest.Service( lambda bag: True if "countx" in bag and bag["countx"].value % 2 else False, "oddFilter") nest.Service(printer, "printer")
help="Output GeV spectra to tab-delimited files") p.add_argument("-t", "--title", dest="title", default=None, help="Spectrum plot title") args = p.parse_args() # Get the TeV source catalog cdir = "/".join([os.environ["HAWC_INSTALL"], "share/hawc/config"]) tevConf = "/".join([cdir, "TeV-src-catalog.xml"]) #gevConf = "/".join([cdir, "1FHL-PS-catalog.xml"]) gevConf = "/".join([cdir, "1FHL-NoTeVCat-PS-catalog.xml"]) # Initialize the framework and a list of point sources nest = HAWCNest() tevSources = grmodel_services.BuildPSCatalog(tevConf, nest.hawcnest_, False) gevSources = grmodel_services.BuildPSCatalog(gevConf, nest.hawcnest_, False) nest.Service("Gilmore09EBLModel", "gilmoreEBL") nest.Configure() # Extract and plot the spectrum of each source mpl.rc("font", family="serif", size=14) fig = plt.figure(1, figsize=(12, 6)) ax = fig.add_subplot(111) crab = "TeV J0534+220 : Crab" scale = 2. crabFlux = 0.
help="Set color scale in log.") # Not Important p.add_argument("-m", "--min", dest="min", type=float, default=None, help="Plot minimum value") p.add_argument("-M", "--max", dest="max", type=float, default=None, help="Plot maximum value") p.add_argument("-n", "--ncolors", dest="ncolors", type=int, default=256, help="Number of colors to use in the color map") args = p.parse_args() # Get Local Sidereal Angle (return other stats) ### hawcnest.SetLoggingLevel(5, False) nest = HAWCNest() nest.Service("StdAstroService", "astro") nest.Service("ConfigDirDetectorService", "det", configDir=os.environ["CONFIG_HAWC"]) nest.Configure() nest.Finish() astro = astro_service.GetService("astro") if args.mjd and args.datetime: print "Only specify MJD or Datetime. Not both!" raise SystemExit if args.mjd: mjd = ModifiedJulianDate(args.mjd*U.day) gps = mjd.timestamp utc = UTCDateTime(gps) elif args.datetime:
class CountKeeper(hawcnest.Module): """Subclassed AERIE module. Take integers in the Bag and store them.""" def __init__(self): hawcnest.Module.__init__(self) self.count = [] self.count2x = [] def Process(self, bag): if "count" in bag and "count2x" in bag: self.count.append(bag["count"].value) self.count2x.append(bag["count2x"].value) return hawcnest.Module.CONTINUE # Create source and module instances nest = HAWCNest() nest.Service(CountInserter, "countInserter", startCount=1, maxCount=22, stepCount=3) nest.Service(CountMultiplier, "countMultiplier", factor=4) nest.Service(CountPrinter, "countPrinter") keeper = CountKeeper() nest.Service(keeper, "countKeeper") # Set up module chain
def main(): """ Main function: execute the program here. """ # Parse command line options p = argparse.ArgumentParser(description="Draw diffuse maps") p.add_argument("fitsFile", nargs="?", help="Cosmic ray anisotropy FITS file") p.add_argument("-e", "--energy", dest="energy", type=float, default=10., help="Map energy [TeV]") p.add_argument("-m", "--mask", dest="mask", action="store_true", default=False, help="Mask out pixels invisible to HAWC") p.add_argument("-n", "--nside", dest="nside", type=int, default=128, help="HEALPix map nside parameter (power of 2)") args = p.parse_args() if not args.fitsFile: p.print_help() return nest = HAWCNest() nest.Service("StdAstroService", "astro") cdir = "/".join([os.environ["HAWC_INSTALL"], "share/hawc/config"]) nest.Service("TabulatedSpectrum", "crabFlux", infilename="/".join([cdir, "CrabICSModel.txt"])) nest.Service("StdRNGService", "rng", seed=12345) nest.Configure() nest.Finish() # Open the GALPROP map and plot the diffuse flux at some energy ct = grmodel_services.CosmicRayAnisotropyTable(args.fitsFile) E = args.energy * TeV nside = args.nside npix = hp.nside2npix(nside) dmap = np.zeros(npix, dtype=float) for i in range(0, npix): z, a = hp.pix2ang(nside, i) d = 90 * degree - z dmap[i] = ct.GetPDF(E, EquPoint(a, d)) if args.mask: if d > 69 * degree or d < -31 * degree: dmap[i] = hp.UNSEEN print 1. - np.min(dmap[dmap != hp.UNSEEN]) mpl.rc("font", family="serif") fig = plt.figure(1) hp.mollview(dmap, fig=1, coord="C", rot=180, title="Cosmic Ray Anisotropy: %g TeV" % args.energy) hp.graticule() plt.show()
# with the hawc-config script: # # # # $> eval `/path/to/aerie/bin/hawc-config --env-sh` # ################################################################################ from hawc import hawcnest, data_structures from hawc.hawcnest import HAWCUnits as U from hawc.data_structures import * from hawc import grmodel_services as grmodel_services from HAWCNest import HAWCNest import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt nest = HAWCNest() nest.Service("Franceschini08EBLModel", "fra08") nest.Service("Gilmore09EBLModel", "gil09") nest.Service("Gilmore12FiducialEBLModel", "gil12a") nest.Service("Gilmore12FixedEBLModel", "gil12b") nest.Configure() fra08 = grmodel_services.GetEBLAbsorptionService("fra08") gil09 = grmodel_services.GetEBLAbsorptionService("gil09") gil12a = grmodel_services.GetEBLAbsorptionService("gil12a") gil12b = grmodel_services.GetEBLAbsorptionService("gil12b") # Create optical depth and attenuation tables for Franceschini model logETeV = np.linspace(-1.4, 2.2, 250) redshift = np.linspace(0.00, 2.00, 250)
"--nside", dest="nside", type=int, default=128, help="HEALPix map nside parameter (power of 2)") p.add_argument("-t", "--ticks", dest="ticks", nargs="+", type=float, help="Ticks to use in plot color bar") p.add_argument("-T", "--title", dest="title", default=None, help="Plot title") args = p.parse_args() # Initialize HAWCNest to create a nice framework nest = HAWCNest() nest.Service("StdAstroService", "astro") cdir = "/".join([os.environ["HAWC_INSTALL"], "share/hawc/config"]) nest.Service("TabulatedSpectrum", "crabFlux", infilename="/".join([cdir, "CrabICSModel.txt"])) nest.Service("StdRNGService", "rng", seed=12345) nest.Configure() nest.Finish() # Open the GALPROP map and plot the diffuse flux at some energy gm = grmodel_services.GALPROPMapTable(args.fitsFile[0])