test_OnOff.py

Martin Pierrick, 03/11/2016 05:57 PM

Download (22.1 KB)

 
1
#! /Applications/Anaconda/bin/python
2
# ====================================================================
3
# This script tests the ON-OFF analysis functionality of the gammalib
4
# ====================================================================
5

    
6
from ctools import *
7
from gammalib import *
8
from math import *
9

    
10
import os
11
import glob
12
import sys
13

    
14
import numpy
15

    
16
# ======================== #
17
# Setup single observation #
18
# ======================== #
19
def single_obs(pntdir, tstart=0.0, duration=1800.0, deadc=0.95, \
20
            emin=0.1, emax=100.0, rad=5.0, \
21
            irf="South_50h", caldb="prod2", id="000000", instrument="CTA"):
22
    """
23
    Returns a single CTA observation.
24

25
    Parameters:
26
     pntdir   - Pointing direction [GSkyDir]
27
    Keywords:
28
     tstart     - Start time [seconds] (default: 0.0)
29
     duration   - Duration of observation [seconds] (default: 1800.0)
30
     deadc      - Deadtime correction factor (default: 0.95)
31
     emin       - Minimum event energy [TeV] (default: 0.1)
32
     emax       - Maximum event energy [TeV] (default: 100.0)
33
     rad        - ROI radius used for analysis [deg] (default: 5.0)
34
     irf        - Instrument response function (default: cta_dummy_irf)
35
     caldb      - Calibration database path (default: "dummy")
36
     id         - Run identifier (default: "000000")
37
     instrument - Intrument (default: "CTA")
38
    """
39
    # Allocate CTA observation
40
    obs_cta = GCTAObservation(instrument)
41

    
42
    # Set calibration database
43
    db = GCaldb()
44
    if (os.path.isdir(caldb)):
45
        db.rootdir(caldb)
46
    else:
47
        db.open("cta", caldb)
48

    
49
    # Set pointing direction
50
    pnt = GCTAPointing()
51
    pnt.dir(pntdir)
52
    obs_cta.pointing(pnt)
53

    
54
    # Set ROI
55
    roi     = GCTARoi()
56
    instdir = GCTAInstDir()
57
    instdir.dir(pntdir)
58
    roi.centre(instdir)
59
    roi.radius(rad)
60

    
61
    # Set GTI
62
    gti = GGti()
63
    gti.append(GTime(tstart), GTime(tstart+duration))
64

    
65
    # Set energy boundaries
66
    ebounds = GEbounds(GEnergy(emin, "TeV"), \
67
                                GEnergy(emax, "TeV"))
68

    
69
    # Allocate event list
70
    events = GCTAEventList()
71
    events.roi(roi)
72
    events.gti(gti)
73
    events.ebounds(ebounds)
74
    obs_cta.events(events)
75

    
76
    # Set instrument response
77
    obs_cta.response(irf, db)
78

    
79
    # Set ontime, livetime, and deadtime correction factor
80
    obs_cta.ontime(duration)
81
    obs_cta.livetime(duration*deadc)
82
    obs_cta.deadc(deadc)
83
    obs_cta.id(id)
84

    
85
    # Return CTA observation
86
    return obs_cta
87

    
88

    
89
# ======================================== #
90
# Add CTA background model to observations #
91
# ======================================== #
92
def add_background_model(models,name="Background",instru="CTA",id="",bgd_file="",bgd_sigma=0.0):
93
    
94
    """
95
    Add CTA background model to a model container.
96

97
    Parameters:
98
     models - a model container
99
     bgd_file - file function for background spectral dependence
100
     bgd_sigma - sigma parameter for the gaussian offset angle dependence of the background rate
101
    """
102
    
103
    # Gaussian radial dependence model
104
    if bgd_sigma > 0.0:
105
        
106
        # Spatial part
107
        bgd_radial = GCTAModelRadialGauss(bgd_sigma)
108
    
109
        # Spectral part
110
        if len(bgd_file) > 0:
111
            bgd_spectrum = GModelSpectralFunc(bgd_file,1.0)
112
        else:
113
            pivot_nrj=GEnergy(1.0e6, "MeV")
114
            bgd_spectrum = GModelSpectralPlaw(1.0e-6, -2.0, pivot_nrj)
115
            bgd_spectrum["Prefactor"].value(61.8e-6)
116
            bgd_spectrum["Prefactor"].scale(1.0e-6)
117
            bgd_spectrum["PivotEnergy"].value(1.0)
118
            bgd_spectrum["PivotEnergy"].scale(1.0e6)
119
            bgd_spectrum["Index"].value(-1.85)
120
            bgd_spectrum["Index"].scale(1.0)
121
    
122
            # Full model
123
            bgd_model = GCTAModelRadialAcceptance(bgd_radial, bgd_spectrum)
124
    
125
    # IRF-defined model
126
    else:
127
        
128
            # Spectral model
129
            pivot_nrj=GEnergy(1.0e6, "MeV")
130
            bgd_spectrum = GModelSpectralPlaw(1.0e-6, -2.0, pivot_nrj)
131
            bgd_spectrum["Prefactor"].value(1.0)
132
            bgd_spectrum["Prefactor"].scale(1.0)
133
            bgd_spectrum["PivotEnergy"].value(1.0)
134
            bgd_spectrum["PivotEnergy"].scale(1.0e6)
135
            bgd_spectrum["Index"].value(0.0)
136
            bgd_spectrum["Index"].scale(1.0)
137
            
138
            # Full model
139
            bgd_model = GCTAModelIrfBackground(bgd_spectrum)
140
    
141
    # Set other background properties
142
    if (len(name) > 0):
143
        bgd_model.name(name)
144
    else:
145
        bgd_model.name("Background")
146
    if (len(instru) > 0):
147
        bgd_model.instruments(instru)
148
    else:
149
        bgd_model.instruments("CTA")
150
    if (len(id) > 0):
151
        bgd_model.ids(id)
152
    
153
    # By default, set model to be fitted
154
    if (len(bgd_file) > 0):
155
        bgd_model['Normalization'].free()
156
    else:
157
        bgd_model['Prefactor'].free()
158
        bgd_model['Index'].free()
159
    
160
    # Add background model to container
161
    models.append(bgd_model)
162
    
163
    # Return model container
164
    return models
165

    
166

    
167
# =========================== #
168
# Set any general type source #
169
# =========================== #
170
def add_source_model(models, name, ra, dec, coord='CEL', \
171
                     skymap='', specfile='', \
172
                     flux=5.7e-16, index=-2.5, pivot=3.0e5, \
173
                     type="point", sigma=1.0, radius=1.0, width=0.1, \
174
                     nnode=0, emin=1.0, emax=10.0, \
175
                     pivot_scale=1e6, flux_scale=1.0e-16):
176
    """
177
    Adds a single point-source with power-law spectrum to a model container.
178
    The default is crab-like.
179

180
    Parameters:
181
     models - a model container
182
     name   - Unique source name
183
     ra     - RA of source location [deg]
184
     dec    - Declination of source location [deg]
185
    Keywords:
186
     flux   - Source flux density in 1.0e-16 ph/cm2/s/MeV
187
     index  - Source spectral index
188
     pivot  - Pivot energy in TeV
189
     type   - Source spatial model
190
     sigma/radius/width  - Spatial model parameters
191
     nnode  - Number of nodes (if > 0, spectral model is a node function)
192
    """
193
    
194
    # Set source spectral model
195
    if (nnode > 0) and (emin != emax):
196
        spectrum = GModelSpectralNodes()
197
        dloge=log10(emax/emin)/nnode
198
        logemin=math.log10(emin)
199
        spectrum.reserve(nnode)
200
        for i in range(nnode):
201
                    enode = GEnergy()
202
                    enode.TeV(10.0**(logemin+(i+0.5)*dloge))
203
                    inode=flux*(enode.MeV()/pivot)**(index)
204
                    spectrum.append(enode, inode)
205
                    spectrum[i*2].scale(pivot_scale)
206
                    spectrum[i*2].fix()
207
                    spectrum[i*2+1].scale(flux_scale)
208
                    spectrum[i*2+1].free()    
209
    # Set source spectral model
210
    elif (len(specfile) > 0):
211
        spectrum = GModelSpectralFunc(specfile)
212
        spectrum["Normalization"].value(1.0)
213
        spectrum["Normalization"].free()
214
    else:
215
        pivot_nrj=GEnergy()
216
        pivot_nrj.TeV(pivot*pivot_scale/1e6)
217
        spectrum = GModelSpectralPlaw(flux, index,pivot_nrj)
218
        spectrum["Prefactor"].scale(flux_scale)
219
        spectrum["Prefactor"].value(flux)
220
        spectrum["Prefactor"].free()
221
        spectrum["PivotEnergy"].scale(pivot_scale)
222
        spectrum["PivotEnergy"].value(pivot)
223
        spectrum["Index"].value(index)
224
        spectrum["Index"].scale(1.0)
225
        spectrum["Index"].free()        
226
        
227
    # Set source spatial model
228
    location = GSkyDir()
229
    if (coord == 'CEL'):
230
        location.radec_deg(ra, dec)
231
    else:
232
        location.lb_deg(ra, dec)    
233
    if (len(skymap) > 0):
234
        spatial = GModelSpatialDiffuseMap(skymap,1.0)
235
        source = GModelSky(spatial, spectrum)
236
        spatial[0].free()
237
    elif type == "point":
238
        spatial = GModelSpatialPointSource(location)
239
        spatial[0].free()
240
        spatial[1].free()
241
        source  = GModelSky(spatial, spectrum)
242
    elif type == "gauss":
243
        radial = GModelSpatialRadialGauss(location, sigma)
244
        radial[0].free()
245
        radial[1].free()
246
        radial[2].free()
247
        source = GModelSky(radial, spectrum)
248
    elif type == "disk":
249
        radial = GModelSpatialRadialDisk(location, radius)
250
        radial[0].free()
251
        radial[1].free()
252
        radial[2].free()
253
        source = GModelSky(radial, spectrum)
254
    elif type == "shell":
255
        radial = GModelSpatialRadialShell(location, radius, width)
256
        radial[0].free()
257
        radial[1].free()
258
        radial[2].free()
259
        radial[3].free()
260
        source = GModelSky(radial, spectrum)
261
    else:
262
        print "ERROR: Unknown source type '"+type+"'."
263
        return None
264
    
265
    # Set source name
266
    source.name(name)
267
    
268
    # Append source model to model container
269
    models.append(source)
270
    
271
    # Return source
272
    return models
273

    
274
# ======================================== #
275
# Set the fit parameters for a given model #
276
# ======================================== #
277
def set_fit_param(model, parname=[], parfit=[], parval=[]):
278
    """
279
    Set the fit parameters for a given model
280
    
281
    Arguments
282
    - model: a model container
283
    - parname: array of parameters names
284
    - parfit: array of fit/fix flags (True=fit,False=fix)
285
    - parval: array of initial/fix parameters values
286
    
287
    Notes
288
    - Arrays should have same numbers of elements
289
    - A way to not set a value but just the fit/fix flag is to pass/leave parval empty
290
    - If among several parameters some values must be set and others not, separate these and call the function two times
291
    """
292

    
293
    # Count/check number of parameters to be set
294
    if (len(parname) != len(parfit)):
295
        print "Incorrect input. Fit parameters not set or modified."
296
        return 0
297
    else:
298
        num_toset=len(parname)
299
                    
300
    # Loop over parameters
301
    for i in range(model.size()):
302
        name=model[i].name()
303
        if (name in parname):
304
            # Get index of matching name
305
            i_par=parname.index(name)
306
            # Set the parameter to be fix/free
307
            if (parfit[i_par]):
308
                model[name].free()
309
            else:
310
                model[name].fix()
311
            # Optionally set the value
312
            if (len(parval) > 0): 
313
                model[name].value(parval[i_par])
314

    
315
    # Exit point
316
    return model
317

    
318

    
319
# ===================== #
320
# Simulate observations #
321
# ===================== #
322
def sim(obs, log=False, debug=False, chatter=2, edisp=False, seed=0, nbins=0,
323
        binsz=0.05, npix=200, proj="TAN", coord="GAL", outfile=""):
324
    """
325
    Simulate events for all observations in the container.
326

327
    Parameters:
328
     obs   - Observation container
329
    Keywords:
330
     log   - Create log file(s)
331
     debug - Create console dump?
332
     edisp - Apply energy dispersion?
333
     seed  - Seed value for simulations (default: 0)
334
     nbins - Number of energy bins (default: 0=unbinned)
335
     binsz - Pixel size for binned simulation (deg/pixel)
336
     npix  - Number of pixels in X and Y for binned simulation
337
    """
338

    
339
    # Allocate ctobssim application and set parameters
340
    sim = ctobssim(obs)
341
    sim["seed"] = seed
342
    sim["edisp"] = edisp
343
    sim["outevents"] = outfile
344

    
345
    # Optionally open the log file
346
    if log:
347
        sim.logFileOpen()
348

    
349
    # Optionally switch-on debugging model
350
    if debug:
351
        sim["debug"] = True
352

    
353
    # Set chatter level
354
    sim["chatter"] = chatter
355

    
356
    # Run ctobssim application. This will loop over all observations in the
357
    # container and simulation the events for each observation. Note that
358
    # events are not added together, they still apply to each observation
359
    # separately.
360
    sim.run()
361

    
362
    # Binned option?
363
    if nbins > 0:
364

    
365
        # Determine common energy boundaries for observations
366
        emin = None
367
        emax = None
368
        for run in sim.obs():
369
            run_emin = run.events().ebounds().emin().TeV()
370
            run_emax = run.events().ebounds().emax().TeV()
371
            if emin == None:
372
                emin = run_emin
373
            elif run_emin > emin:
374
                emin = run_emin
375
            if emax == None:
376
                emax = run_emax
377
            elif run_emax > emax:
378
                emax = run_emax
379

    
380
        # Allocate ctbin application and set parameters
381
        bin = ctbin(sim.obs())
382
        bin["ebinalg"] = "LOG"
383
        bin["emin"] = emin
384
        bin["emax"] = emax
385
        bin["enumbins"] = nbins
386
        bin["usepnt"] = True # Use pointing for map centre
387
        bin["nxpix"] = npix
388
        bin["nypix"] = npix
389
        bin["binsz"] = binsz
390
        bin["coordsys"] = coord
391
        bin["proj"] = proj
392

    
393
        # Optionally open the log file
394
        if log:
395
            bin.logFileOpen()
396

    
397
        # Optionally switch-on debugging model
398
        if debug:
399
            bin["debug"] = True
400

    
401
        # Set chatter level
402
        bin["chatter"] = chatter
403

    
404
        # Run ctbin application. This will loop over all observations in
405
        # the container and bin the events in counts maps
406
        bin.run()
407

    
408
        # Make a deep copy of the observation that will be returned
409
        # (the ctbin object will go out of scope one the function is
410
        # left)
411
        obs = bin.obs().copy()
412

    
413
    else:
414

    
415
        # Make a deep copy of the observation that will be returned
416
        # (the ctobssim object will go out of scope one the function is
417
        # left)
418
        obs = sim.obs().copy()
419
        
420
    # Optionally save file
421
    if (len(outfile) > 0):
422
        sim.save()
423
        
424
    # Delete the simulation
425
    del sim
426

    
427
    # Return observation container
428
    return obs
429

    
430

    
431
# =================== #
432
# Make a simple model #
433
# =================== #
434
def make_simple_model(models,name,ra,dec,flux,idx):
435
    
436
    # Add background model (one for each pointing)
437
    models = add_background_model(models,bgd_sigma=0.0,instru='CTA',id="0001",name="Background left")
438
    set_fit_param(models["Background left"],parname=['Sigma','Normalization','Prefactor','Index'],parfit=[False,True,True,False])
439
    models = add_background_model(models,bgd_sigma=0.0,instru='CTA',id="0002",name="Background right")
440
    set_fit_param(models["Background right"],parname=['Sigma','Normalization','Prefactor','Index'],parfit=[False,True,True,False])
441
    
442
    # Add source model
443
    models = add_source_model(models, name, ra, dec, flux=flux, index=idx, pivot=1.0e6, type="point", pivot_scale=1e6, flux_scale=1.0e-16)
444
    set_fit_param(models["Test source"],parname=['Prefactor','Index','RA','DEC'],parfit=[True,True,False,False])
445
    
446
    # Exit
447
    return models
448
    
449

    
450
# =================== #
451
# Make a simple model #
452
# =================== #
453
def reset_simple_model(models,ra,dec,flux,idx):
454
    
455
    # Add background model (one for each pointing)
456
    set_fit_param(models["Background left"],parname=['Sigma','Normalization','Prefactor','Index'],parfit=[False,True,True,False],parval=[4.0,1.0,1.0,0.0])
457
    set_fit_param(models["Background right"],parname=['Sigma','Normalization','Prefactor','Index'],parfit=[False,True,True,False],parval=[4.0,1.0,1.0,0.0])
458
    set_fit_param(models["Test source"],parname=['Prefactor','Index','RA','DEC'],parfit=[True,True,False,False],parval=[flux,idx,ra,dec])
459
    
460
    # Exit
461
    return models
462

    
463

    
464
# ===================== #
465
# Print out fit results #
466
# ===================== #
467
def print_fit_results(obslist):
468
    
469
    # Print
470
    print "Background left prefactor: %.3e +/- %.3e " % (obslist.models()["Background left"]['Prefactor'].value(),obslist.models()["Background left"]['Prefactor'].error())
471
    print "Background left index: %.3e +/- %.3e " % (obslist.models()["Background left"]['Index'].value(),obslist.models()["Background left"]['Index'].error())
472
    print "Background right prefactor: %.3e +/- %.3e " % (obslist.models()["Background right"]['Prefactor'].value(),obslist.models()["Background right"]['Prefactor'].error())
473
    print "Background right index: %.3e +/- %.3e " % (obslist.models()["Background right"]['Index'].value(),obslist.models()["Background right"]['Index'].error())
474
    print "Source prefactor: %.3e +/- %.3e " % (obslist.models()["Test source"]['Prefactor'].value(),obslist.models()["Test source"]['Prefactor'].error())
475
    print "Source index: %.3e +/- %.3e " % (obslist.models()["Test source"]['Index'].value(),obslist.models()["Test source"]['Index'].error())
476
    print "Fit ended with value %.3e and status %d after %d iterations." % (opt.value(),opt.status(),opt.iter())
477
    
478
    # Exit
479
    return
480
    
481

    
482
#=====================#
483
# Routine entry point #
484
#=====================#
485
if __name__ == '__main__':
486

    
487
    """
488
    Aims:
489
    This script tests the ON-OFF analysis functionality of the gammalib
490
    
491
    Arguments:
492
    - None
493
    
494
    Notes:
495
    - Hard-coded source, observations, and regions (more flexible script later...)
496
    - Approximate method to set OFF regions (works only on equator)
497
    - Have to set up path to data base (db and irf)
498
    - Source flux set as flux density at 1TeV
499
    """
500
    
501
    # Job parameters
502
    # CTA
503
    db="prod2"
504
    irf="South_50h"
505
    bgd=""
506
    rsp_sigma=4.0
507
    bgd_sigma=4.0
508
    duration=1800.0
509
    rad=5.0
510
    # Energy
511
    emin=0.1
512
    emax=100.0
513
    nbins=9
514
    nnodes=5
515
    # Source
516
    name="Test source"
517
    ra=0.0
518
    dec=0.0
519
    flux=5.0e-17
520
    idx=-2.5
521
    dflux=1.5  # Offset factor by which true value is rescaled before fit
522
    didx=0.3   # Offset factor by which true value is rescaled before fit
523
    # ON-OFF
524
    onshift=1.0
525
    onsize=0.3
526
    noff=3
527
    # Others
528
    chatter=4
529
    seed=10
530
    Check=False
531
    
532
    # Create observation container
533
    obslist = GObservations()
534
    
535
    # Add two offset observations
536
    leftdir = GSkyDir()
537
    leftdir.radec_deg(ra+onshift, dec)
538
    obs=single_obs(leftdir, tstart=0.0, duration=duration, deadc=0.95, \
539
                   emin=emin, emax=emax, rad=rad, \
540
                   irf=irf, caldb=db, id="000000", instrument="CTA")
541
    obs.name("Left")
542
    obs.id("0001")
543
    obslist.append(obs)
544
    rightdir = GSkyDir()
545
    rightdir.radec_deg(ra-onshift, dec)
546
    obs=single_obs(rightdir, tstart=0.0, duration=duration, deadc=0.95, \
547
                   emin=emin, emax=emax, rad=rad, \
548
                   irf=irf, caldb=db, id="000000", instrument="CTA")
549
    obs.name("Right")
550
    obs.id("0002")
551
    obslist.append(obs)    
552
    
553
    # Create a model container
554
    models = GModels()   
555
    # Make a simple model for two observations
556
    models = make_simple_model(models,name,ra,dec,flux,idx)
557
    # Add model to the container
558
    obslist.models(models)
559
    obslist.models().save("sim_model.xml")
560
    
561
    # Make event list
562
    obslist = sim(obslist, log=False, debug=False, chatter=chatter, edisp=False, seed=seed, nbins=0, outfile='onoff_events.xml')
563
    
564
    # Define ON region
565
    ondir = GSkyDir()
566
    ondir.radec_deg(0.0,0.0)
567
    on = GSkyRegions()
568
    onreg=GSkyRegionCircle(ondir,onsize)
569
    on.append(onreg)
570
    on.save("on_regions.reg")
571
    
572
    # Define OFF regions
573
    offleft = GSkyRegions()
574
    offright = GSkyRegions()
575
    for i in range(noff):
576
        phi=(i+1)*360./(noff+1.0)
577
        # Left pointing  
578
        offdir = GSkyDir(leftdir)       
579
        offdir.rotate_deg(phi-90., onshift)
580
        offreg=GSkyRegionCircle(offdir, onsize)
581
        offleft.append(offreg)
582
        # Right pointing
583
        offdir = GSkyDir(rightdir)       
584
        offdir.rotate_deg(phi+90.0, onshift)       
585
        offreg=GSkyRegionCircle(offdir, onsize)
586
        offright.append(offreg)
587
       
588
    offleft.save("off_left_regions.reg")
589
    offright.save("off_right_regions.reg")
590
      
591
    # Create ON-OFF analysis object
592
    onofflist = GCTAOnOffObservations()
593
    
594
    # Define energy binning
595
    etrue = GEbounds(nbins, GEnergy(emin, "TeV"), GEnergy(emax, "TeV"))
596
    ereco = GEbounds(nbins, GEnergy(emin, "TeV"), GEnergy(emax, "TeV"))
597
    
598
    # Append ON-OFF observations
599
    obs=GCTAOnOffObservation(ereco, on, offleft)
600
    obs.name("Left")
601
    obs.id("0001")
602
    onofflist.append(obs)
603
    obs=GCTAOnOffObservation(ereco, on, offright)
604
    obs.name("Right")
605
    obs.id("0002")
606
    onofflist.append(obs)
607
    
608
    # Load data and save
609
    # (fills ON and OFF spectra, ON and OFF observing time, and alpha parameter)
610
    onofflist[0].fill(obslist[0])
611
    onofflist[1].fill(obslist[1])
612
    onofflist[0].off_spec().save("offspec_left.fits")
613
    onofflist[0].on_spec().save("onspec_left.fits")
614
    onofflist[1].off_spec().save("offspec_right.fits")
615
    onofflist[1].on_spec().save("onspec_right.fits")
616

    
617
        # Compute responses and save
618
    onofflist[0].compute_response(obslist[0],models,etrue)
619
    onofflist[1].compute_response(obslist[1],models,etrue)    
620
    onofflist[0].arf().save("arf_left.fits")
621
    onofflist[0].rmf().save("rmf_left.fits")  
622
    onofflist[1].arf().save("arf_right.fits")
623
    onofflist[1].rmf().save("rmf_right.fits")
624
    
625
    # Save ON-OFF observations
626
    onofflist.save("onoffobservations.xml")
627
        
628
    # Check times
629
    if Check:
630
        print "Observation %s with %.1fs ON time and %.1fs OFF time" % (onofflist[0].name(),onofflist[0].ontime(),onofflist[0].offtime())
631
        print "Observation %s with %.1fs ON time and %.1fs OFF time" % (onofflist[1].name(),onofflist[1].ontime(),onofflist[1].offtime())   
632
        # Check spectra
633
        print '\nLeft'
634
        for i in range(nbins):
635
                print "ON counts %d - OFF counts %d" % (onofflist[0].on_spec()[i],onofflist[0].off_spec()[i])
636
        print '\nRight'
637
        for i in range(nbins):
638
                print "ON counts %d - OFF counts %d" % (onofflist[1].on_spec()[i],onofflist[1].off_spec()[i])
639
        print '\n'   
640
        # Check responses
641
        print 'Left'
642
        for i in range(nbins):
643
                print "ARF %.3e - BGD %.3e" % (onofflist[0].arf()[i],onofflist[0].bgd()[i])
644
        print '\nRight'
645
        for i in range(nbins):
646
                print "ARF %.3e - BGD %.3e" % (onofflist[1].arf()[i],onofflist[1].bgd()[i])
647
       
648
    # Reset model container and append it to observation list
649
    models=reset_simple_model(models,ra,dec,dflux*flux,idx-didx)
650
    onofflist.models(models)
651
    
652
    # Set optimizer and logger
653
    log=GLog('fit_onoff.log',True)
654
    log.chatter(chatter)
655
    opt=GOptimizerLM(log)
656
    
657
    # Optimize for ON-OFF analysis
658
    print '\nON-OFF fitting...'
659
    onofflist.optimize(opt)
660
    onofflist.errors(opt)
661
    print_fit_results(onofflist)
662
    
663
    # Free memory
664
    del opt
665
    del log
666
         
667
    # Reset model container and append it to observation list
668
    models=reset_simple_model(models,ra,dec,dflux*flux,idx-didx)
669
    obslist.models(models)
670
    
671
    # Set optimizer and logger
672
    log=GLog('fit_unbinned.log',True)
673
    log.chatter(chatter)
674
    opt=GOptimizerLM(log)
675
    
676
    # Optimize for Fermi-style analysis
677
    print '\nUnbinned fitting...'
678
    obslist.optimize(opt)
679
    obslist.errors(opt)
680
    print_fit_results(obslist)
681
    
682
    # Free memory
683
    del opt
684
    del log
685
    
686