def name_to_spectral_dict(like, name, errors=False, minos_errors=False, covariance_matrix=False): print name source = get_gtlike_source(like, name) spectrum = source.spectrum() d = gtlike_spectrum_to_dict(spectrum, errors) if minos_errors: parameters = ParameterVector() spectrum.getParams(parameters) for p in parameters: pname = p.getName() if p.isFree(): lower, upper = like.minosError(name, pname) try: d['%s_lower_err' % pname] = -1 * lower * p.getScale() d['%s_upper_err' % pname] = upper * p.getScale() except Exception, ex: print 'ERROR computing Minos errors on parameter %s for source %s:' % ( pname, name), ex traceback.print_exc(file=sys.stdout) d['%s_lower_err' % pname] = np.nan d['%s_upper_err' % pname] = np.nan else: d['%s_lower_err' % pname] = np.nan d['%s_upper_err' % pname] = np.nan
def get_covariance_matrix(like, name): """ Get the covarince matrix. We can mostly get this from FluxDensity, but the covariance matrix returned by FluxDensity is only for the free paramters. Here, we transform it to have the covariance matrix for all parameters, and set the covariance to 0 when the parameter is free. """ # source = like.logLike.getSource(name) source = get_gtlike_source(like, name) spectrum = source.spectrum() parameters = ParameterVector() spectrum.getParams(parameters) free = np.asarray([p.isFree() for p in parameters]) scales = np.asarray([p.getScale() for p in parameters]) scales_transpose = scales.reshape((scales.shape[0], 1)) cov_matrix = np.zeros([len(parameters), len(parameters)]) try: fd = FluxDensity(like, name) cov_matrix[np.ix_(free, free)] = fd.covar # create absolute covariance matrix: cov_matrix = scales_transpose * cov_matrix * scales except RuntimeError, ex: if ex.message == 'Covariance matrix has not been computed.': pass else: raise ex
def spectrum_to_dict(spectrum): """ Convert a pyLikelihood object to a python dictionary which can be easily saved to a file. """ parameters = ParameterVector() spectrum.getParams(parameters) d = dict(name=spectrum.genericName(), method='gtlike') for p in parameters: d[p.getName()] = p.getTrueValue() return d
def gtlike_spectrum_to_dict(spectrum, errors=False): """ Convert a pyLikelihood object to a python dictionary which can be easily saved to a file. """ parameters=ParameterVector() spectrum.getParams(parameters) d = dict(name = spectrum.genericName(), method='gtlike') for p in parameters: d[p.getName()]= p.getTrueValue() if errors: d['%s_err' % p.getName()]= p.error()*p.getScale() if p.isFree() else np.nan if d['name'] == 'FileFunction': ff=pyLikelihood.FileFunction_cast(spectrum) d['file']=ff.filename() return d