def _get_reco_kernels(self, kernelfile=None, **kwargs): for reco_scale in ['e_reco_scale', 'cz_reco_scale']: if reco_scale in kwargs: if not kwargs[reco_scale]==1: raise ValueError('%s = %.2f not valid for RecoServiceKernelFile!' %(reco_scale, kwargs[reco_scale])) if not kernelfile in [self.kernelfile, None]: logging.info('Reconstruction from non-default kernel file %s!'%kernelfile) return fileio.from_file(find_resource(kernelfile)) if not hasattr(self, 'kernels'): logging.info('Using file %s for default reconstruction'%(kernelfile)) self.kernels = fileio.from_file(find_resource(kernelfile)) return self.kernels
def kernel_from_simfile(self, simfile=None, **kwargs): logging.info('Opening file: %s'%(simfile)) try: fh = h5py.File(find_resource(simfile),'r') except IOError,e: logging.error("Unable to open event data file %s"%simfile) logging.error(e) sys.exit(1)
def get_pid_kernels(self, pid_kernelfile=None, **kwargs): logging.info('Opening file: %s' % (pid_kernelfile)) try: self.pid_kernels = from_json(find_resource(pid_kernelfile)) except IOError, e: logging.error("Unable to open kernel file %s" % pid_kernelfile) logging.error(e) sys.exit(1)
def __init__(self, ebins, czbins, detector_depth=None, earth_model=None, prop_height=None, oversample_e=None, oversample_cz=None, gpu_id=None, **kwargs): """ \params: * ebins: Energy bin edges * czbins: cos(zenith) bin edges * earth_model: Earth density model used for matter oscillations. * detector_depth: Detector depth in km. * prop_height: Height in the atmosphere to begin in km. * gpu_id: If running on a system with multiple GPUs, it will choose the one with gpu_id. Otherwise, defaults to default context """ self.gpu_id = gpu_id try: import pycuda.autoinit self.context = cuda.Device(self.gpu_id).make_context() print "Initializing PyCUDA using gpu id: %d" % self.gpu_id except: import pycuda.autoinit print "Auto initializing PyCUDA..." #mfree,mtot = cuda.mem_get_info() #print "free memory: %s mb",mfree/1.0e6 #print "tot memory: %s mb",mtot/1.0e6 #raw_input("PAUSED...") logging.info('Instantiating %s' % self.__class__.__name__) self.ebins = np.array(ebins) self.czbins = np.array(czbins) self.prop_height = prop_height for ax in [self.ebins, self.czbins]: if (len(np.shape(ax)) != 1): raise IndexError('Axes must be 1d! ' + str(np.shape(ax))) report_params(get_params(), ['km', '', '', '', '']) earth_model = find_resource(earth_model) self.earth_model = earth_model self.FTYPE = np.float64 self.ebins_fine = oversample_binning(self.ebins, oversample_e) self.czbins_fine = oversample_binning(self.czbins, oversample_cz) self.ecen_fine = get_bin_centers(self.ebins_fine) self.czcen_fine = get_bin_centers(self.czbins_fine) self.initialize_kernel(detector_depth, **kwargs) return
def get_osc_probLT_dict_hdf5(filename): ''' Returns a dictionary of osc_prob_maps from the lookup table .hdf5 files. ''' try: fh = h5py.File(find_resource(filename), 'r') except IOError, e: logging.error("Unable to open oscillation map file %s" % filename) logging.error(e) sys.exit(1)
def __init__(self, ebins, czbins, aeff_weight_file=None, **kwargs): self.ebins = ebins self.czbins = czbins logging.info('Initializing AeffServiceMC...') logging.info('Opening file: %s' % (aeff_weight_file)) try: fh = h5py.File(find_resource(aeff_weight_file), 'r') except IOError, e: logging.error("Unable to open aeff_weight_file %s" % aeff_weight_file) logging.error(e) sys.exit(1)
def get_pid_kernels(self, pid_paramfile=None, PID_offset=0., PID_scale=1., **kwargs): # load parametrization file logging.info('Opening PID parametrization file %s' % pid_paramfile) try: param_str = from_json(find_resource(pid_paramfile)) except IOError, e: logging.error("Unable to open PID parametrization file %s" % pid_paramfile) logging.error(e) sys.exit(1)
def get_earth_model(self, model): """ Check whether the specified Earth density profile has a correct NuCraft preface. If not, create a temporary file that does. """ logging.debug('Trying to construct Earth model from "%s"'%model) try: resource_path = find_resource(model) self.earth_model = EarthModel(resource_path) logging.info('Loaded Earth model from %s'%model) except SyntaxError: #Probably the file is lacking the correct preamble logging.info('Failed to construct NuCraft Earth model directly from' ' %s! Adding default preamble...'%resource_path) #Generate tempfile with preamble with open(resource_path, 'r') as infile: profile_lines = infile.readlines() preamble = ['# nuCraft Earth model with PREM density ' 'values for use as template; keep structure ' 'of the first six lines unmodified!\n', '(0.4656,0.4656,0.4957) # tuple of (relative) ' #'(0.5, 0.5, 0.5) # tuple of (relative) ' 'electron numbers for mantle, outer core, ' 'and inner core\n', '6371. # radius of the Earth\n', '3480. # radius of the outer core\n', '1121.5 # radius of the inner core\n', '# two-columned list of radii and corresponding ' 'matter density values in km and kg/dm^3; ' 'add, remove or modify lines as necessary\n'] tfile = NamedTemporaryFile() tfile.writelines(preamble+profile_lines) tfile.flush() try: self.earth_model = EarthModel(tfile.name) except: logging.error('Could not construct Earth model from %s: %s' %(model, sys.exc_info()[1])) sys.exit(1) logging.info('Successfully constructed Earth model') tfile.close() except IOError: logging.info('Using NuCraft built-in Earth model "%s"'%model) self.earth_model = EarthModel(model)
def __init__(self, ebins, czbins, reco_param_file=None, **kwargs): """ Parameters needed to instantiate a reconstruction service with parametrizations: * ebins: Energy bin edges * czbins: cos(zenith) bin edges * reco_param_file: JSON containing the parametrizations """ # Load parametrization logging.info('Opening reconstruction parametrization file %s' % reco_param_file) # Needed for self.read_param_string() self.ebins = ebins self.czbins = czbins # Get parametrization param_str = from_json(find_resource(reco_param_file)) self.parametrization = self.read_param_string(param_str) # No **kwargs, so stored kernels will always have reco scales 1.0 RecoServiceBase.__init__(self, ebins, czbins, **kwargs)
def __init__(self, ebins, czbins, aeff_egy_par, aeff_coszen_par, **params): ''' Parameters: * aeff_egy_par - effective area vs. Energy 1D parameterizations for each flavor, in a text file (.dat) * aeff_coszen_par - json file containing 1D coszen parameterization for each flavor ''' logging.info('Initializing AeffServicePar...') self.ebins = ebins self.czbins = czbins ## Load the info from .dat files into a dict... ## Parametric approach treats all NC events the same aeff_coszen_par_str = from_json(find_resource(aeff_coszen_par)) aeff2d_nc = self.get_aeff_flavor('NC', aeff_egy_par, aeff_coszen_par_str) aeff2d_nc_bar = self.get_aeff_flavor('NC_bar', aeff_egy_par, aeff_coszen_par_str) self.aeff_dict = {} logging.info("Creating effective area parametric dict...") for flavor in [ 'nue', 'nue_bar', 'numu', 'numu_bar', 'nutau', 'nutau_bar' ]: flavor_dict = {} logging.debug("Working on %s effective areas" % flavor) aeff2d = self.get_aeff_flavor(flavor, aeff_egy_par, aeff_coszen_par_str) flavor_dict['cc'] = aeff2d flavor_dict['nc'] = aeff2d_nc_bar if 'bar' in flavor else aeff2d_nc self.aeff_dict[flavor] = flavor_dict return
def __init__(self, ebins, czbins, detector_depth=None, earth_model=None, prop_height=None, **kwargs): """ Parameters needed to instantiate a Prob3OscillationService: * ebins: Energy bin edges * czbins: cos(zenith) bin edges * earth_model: Earth density model used for matter oscillations. * detector_depth: Detector depth in km. * prop_height: Height in the atmosphere to begin in km. """ OscillationServiceBase.__init__(self, ebins, czbins) logging.info('Initializing %s...' % self.__class__.__name__) report_params(get_params(), ['km', '', 'km']) self.prop_height = prop_height earth_model = find_resource(earth_model) self.barger_prop = BargerPropagator(earth_model, detector_depth) self.barger_prop.UseMassEigenstates(False)
parser.add_argument('-v', '--verbose', action='count', default=None, help='''set verbosity level''') args = parser.parse_args() #Set verbosity level set_verbosity(args.verbose) #Check binning ebins, czbins = check_binning(args.osc_flux_maps) logging.info("Defining aeff_service...") if args.mc_mode: logging.info(" Using effective area from EVENT DATA...") aeff_service = AeffServiceMC(ebins, czbins, aeff_weight_file=args.weighted_aeff_file) else: logging.info(" Using effective area from PARAMETRIZATION...") aeff_settings = from_json(find_resource(args.settings_file)) aeff_service = AeffServicePar(ebins, czbins, **aeff_settings) event_rate_maps = get_event_rates(args.osc_flux_maps, aeff_service, args.livetime, args.aeff_scale) logging.info("Saving output to: %s" % args.outfile) to_json(event_rate_maps, args.outfile)
def _get_reco_kernels(self, reco_vbwkde_evts_file=None, evts_dict=None, reco_vbwkde_make_plots=False, **kwargs): """Given a reco events resource (resource file name or dictionary), retrieve data from it then serialize and hash the data. If the object attribute kernels were computed from the same source data, simply return those. Otherwise, compute the kernels anew and return them. Arguments --------- NOTE: One--and only one--of the two arguments must be specified. reco_vbwkde_evts_file : str (or dict) Name or path to file containing event reco info. See doc for __init__ method for details about contents. If a dict is passed in, it is automatically populated to evts_dict (see below). evts_dict : dict Dictionary containing event reco info. Allows user to pass in a non-string-object to avoid re-loading a file to check whether the contents have changed each time. See doc for __init__ method for details about the dictionary's format. reco_vbwkde_make_plots : bool """ if not isinstance(reco_vbwkde_make_plots, bool): raise ValueError( "Option reco_vbwkde_make_plots must be specified and of bool type" ) for reco_scale in ['e_reco_scale', 'cz_reco_scale']: if reco_scale in kwargs and kwargs[reco_scale] != 1: raise ValueError( '%s = %.2f, must be 1.0 for RecoServiceVBWKDE!' % (reco_scale, kwargs[reco_scale])) REMOVE_SIM_DOWNGOING = True if (reco_vbwkde_evts_file is not None) and (evts_dict is not None): raise TypeError( 'One--and only one--of {reco_vbwkde_evts_file|evts_dict} ' + 'may be specified') if isinstance(reco_vbwkde_evts_file, dict): evts_dict = reco_vbwkde_evts_file evts_dict = None if isinstance(reco_vbwkde_evts_file, str): logging.info('Constructing VBWKDEs from event true & reco ' + 'info in file: %s' % reco_vbwkde_evts_file) fpath = find_resource(reco_vbwkde_evts_file) eventsdict = hdf.from_hdf(fpath) new_hash = utils.hash_file(fpath) elif isinstance(evts_dict, dict): eventsdict = evts_dict new_hash = utils.hash_obj(eventsdict) else: raise TypeError('A {reco_vbwkde_evts_file|evts_dict} must be' + 'provided, where the former must be a str ' + 'and the latter must be a dict.') if (self.kernels is not None) and (new_hash == self.reco_events_hash): return self.kernels self.kernels = self.all_kernels_from_events( eventsdict=eventsdict, remove_sim_downgoing=REMOVE_SIM_DOWNGOING, make_plots=reco_vbwkde_make_plots) self.reco_events_hash = new_hash return self.kernels
def trace(self, message, *args, **kws): self.log(logging.TRACE, message, *args, **kws) logging.Logger.trace = trace logging.RootLogger.trace = trace logging.trace = logging.root.trace #Don't move these up, as "trace" might be used in them from pisa.utils.jsons import from_json from pisa.resources.resources import find_resource #Get the logging configuration #Will search in local dir, $PISA and finally package resources logconfig = from_json(find_resource('logging.json')) #Setup the logging system with this config logging.config.dictConfig(logconfig) #Make the loggers public #In case they haven't been defined, this will just inherit from the root logger physics = logging.getLogger('physics') profile = logging.getLogger('profile') def set_verbosity(verbosity): '''Overwrite the verbosity level for the root logger Verbosity should be an integer with the levels just below. ''' #Ignore if no verbosity is given
'deltacp': args.deltacp, 'deltam21': args.deltam21, 'deltam31': args.deltam31, 'theta12': args.theta12, 'theta13': args.theta13, 'theta23': args.theta23 } report_params(osc_params, units=['rad', 'eV^2', 'eV^2', 'rad', 'rad', 'rad']) # Initialize binning for prob maps: ebins = np.linspace(1, 80, 150) czbins = np.linspace(-1, 0, 150) # Initialize barger propagator which contains the methods for # extracting the oscillation probabilities through the earth. earth_model = find_resource(args.earth_model) barger_prop = BargerPropagator(earth_model, args.detector_depth) barger_prop.UseMassEigenstates(False) mAtm = args.deltam31 if args.deltam31 < 0.0 else (args.deltam31 - args.deltam21) # Set to false, since we are using sin^2(2 theta) variables kSquared = False sin2th12Sq = np.sin(2.0 * args.theta12)**2 sin2th13Sq = np.sin(2.0 * args.theta13)**2 sin2th23Sq = np.sin(2.0 * args.theta23)**2 neutrinos = ['nue', 'numu', 'nutau'] anti_neutrinos = ['nue_bar', 'numu_bar', 'nutau_bar'] nu_barger = {