After doing a fit with Sherpa you may want to dump all the results to a file for later processing or inspection.  The following snippet writes the results from model fitting and confidence estimation to a file using the JSON format for data serialization.  This format is widely supported in other programming languages and is also human-readable.

import json
from sherpa.astro.ui import get_source, get_fit_results, get_conf_results

src = get_source()
fit = get_fit_results()
conf = get_conf_results()
              
src_par_attrs = ('name', 'frozen', 'modelname', 'units', 'val', 'fullname')
fit_attrs = ('methodname', 'statname', 'succeeded', 'statval', 'numpoints', 'dof',
       'rstat', 'qval', 'nfev', 'message', 'parnames', 'parvals')
conf_attrs = ('datasets', 'methodname', 'fitname', 'statname', 'sigma', 'percent',
       'parnames', 'parvals', 'parmins', 'parmaxes', 'nfits')

out = dict()
out['src'] = dict(name=src.name,
         pars=[dict((attr, getattr(par, attr)) for attr in src_par_attrs)
            for par in src.pars])
out['fit'] = dict((attr, getattr(fit, attr)) for attr in fit_attrs)
out['conf'] = dict((attr, getattr(conf, attr)) for attr in conf_attrs)
out['pars'] = []

for par in src.pars:
  fullname = par.fullname
  if any(fullname == x['name'] for x in out['pars']):
    continue  # Parameter was already processed
  outpar = dict(name=fullname, kind=par.name)

  # None implies no calculated confidence interval for Measurement
  parmin = None          
  parmax = None
  if fullname in conf.parnames:  # Confidence limits available from conf
    i = conf.parnames.index(fullname)
    parval = conf.parvals[i]
    parmin = conf.parmins[i]
    parmax = conf.parmaxes[i]
    if parmin == None:
      parmin = -float('inf') # None from conf means infinity, so set accordingly
    if parmax == None:
      parmax = float('inf')
  elif fullname in fit.parnames: # Conf failed or par is uninteresting and wasn't sent to conf
    i = fit.parnames.index(fullname)
    parval = fit.parvals[i]
  else:              # No fit or conf value (maybe frozen)
    parval = par.val
  out['pars'].append(outpar)

json.dump(out, open('sherpa_results.json', 'w'), sort_keys=True, indent=4)



    5           8