How to use the mc3.utils.Log function in mc3

To help you get started, we’ve selected a few mc3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pcubillos / mc3 / tests / test_logging.py View on Github external
def test_tracklev(tmp_path):
    verb = 2
    log_file = str(tmp_path / 'test.log')

    log = mu.Log(log_file, verb=verb)
    with pytest.raises(SystemExit):
        log.error('Error', tracklev=1)

    with open(log_file, 'r') as f:
        content = f.read()
    assert "Error in module: '__init__.py', function: 'main', line:" in content
github pcubillos / mc3 / tests / test_logging.py View on Github external
def test_context_manager(capsys):
    msg = 'Hello, this is log'
    with mu.Log() as log:
        log.msg(msg)
    captured = capsys.readouterr()
    assert captured.out == msg + '\n'
github pcubillos / mc3 / tests / test_logging.py View on Github external
def test_log_error(tmp_path):
    verb = 2
    log_file = str(tmp_path / 'test.log')

    log = mu.Log(log_file, verb=verb)
    log.debug('Debugging')
    log.msg('Hello, this is log')
    log.head('Headline')
    log.warning('Warning!')

    with pytest.raises(SystemExit):
        log.error('Error')  # Line number in log_content must match this one

    with open(log_file, 'r') as f:
        content = f.read()
    assert content == '\n'.join(log_content[3-verb:])
github pcubillos / mc3 / tests / test_logging.py View on Github external
def test_log(tmp_path, verb):
    log_file = str(tmp_path / 'test.log')

    log = mu.Log(log_file, verb=verb)
    log.debug('Debugging')
    log.msg('Hello, this is log')
    log.head('Headline')
    log.warning('Warning!')
    log.close()

    with open(log_file, 'r') as f:
        content = f.read()
    assert content == '\n'.join(log_content[3-verb:4])
github pcubillos / mc3 / mc3 / fit_driver.py View on Github external
[ 4.57471072 -2.28357843  0.48341911]
  92.79923183159411
  92.79923183159411

  >>> # Fit with priors (Gaussian, uniform, uniform):
  >>> prior    = np.array([4.0, 0.0, 0.0])
  >>> priorlow = np.array([0.1, 0.0, 0.0])
  >>> priorup  = np.array([0.1, 0.0, 0.0])
  >>> output = mc3.fit(data, uncert, quad, params, indparams=[x],
          prior=prior, priorlow=priorlow, priorup=priorup)
  >>> print(output['bestp'], output['best_chisq'], -2*output['best_log_post'], sep='\n')
  [ 4.01743461 -2.00989433  0.45686521]
  93.77082119449915
  93.80121777303248
  """
  with mu.Log() as log:
      if leastsq not in [None, 'lm', 'trf']:
          log.error("Invalid 'leastsq' input ({}). Must select from "
                    "['lm', 'trf'].".format(leastsq))

  # Total number of model parameters:
  npars = len(params)
  # Default pstep:
  if pstep is None:
      pstep = np.ones(npars, np.double)
  # Default boundaries (all parameter space):
  if pmin is None:
      pmin = np.tile(-np.inf, npars)
  if pmax is None:
      pmax = np.tile(np.inf,  npars)
  # Default priors, must set all or no one:
  if prior is None or priorlow is None or priorup is None:
github pcubillos / mc3 / mc3 / sampler_driver.py View on Github external
>>>     prior=prior, priorlow=priorlow, priorup=priorup,
  >>>     leastsq='lm', nsamples=1e5, burnin=1000, plots=True)

  >>> # Nested sampling:
  >>> ns_output = mc3.sample(data, uncert, func, params, indparams=indparams,
  >>>     sampler='dynesty', pstep=pstep, ncpu=ncpu, pmin=pmin, pmax=pmax,
  >>>     prior=prior, priorlow=priorlow, priorup=priorup,
  >>>     leastsq='lm', plots=True)

  >>> # See more examples and details at:
  >>> # https://mc3.readthedocs.io/en/latest/mcmc_tutorial.html
  >>> # https://mc3.readthedocs.io/en/latest/ns_tutorial.html
  """
  # Logging object:
  if isinstance(log, str):
      log = mu.Log(log, append=resume)
      closelog = True
  else:
      closelog = False
      if log is None:
          log = mu.Log()

  log.msg("\n{:s}\n"
      "  Multi-core Markov-chain Monte Carlo (MC3).\n"
      "  Version {}.\n"
      "  Copyright (c) 2015-{:d} Patricio Cubillos and collaborators.\n"
      "  MC3 is open-source software under the MIT license (see LICENSE).\n"
      "{:s}\n\n".format(log.sep, __version__, date.today().year, log.sep))

  # Deprecation warnings (to be removed not before summer 2020):
  if parname is not None:
      log.warning("parname argument is deprecated. Use pnames instead.")
github pcubillos / mc3 / mc3 / stats / stats.py View on Github external
-------
    >>> import numpy as np
    >>> import mc3.stats as ms
    >>> # Test for a Normal distribution:
    >>> npoints = 100000
    >>> posterior = np.random.normal(0, 1.0, npoints)
    >>> pdf, xpdf, HPDmin = ms.cred_region(posterior)
    >>> # 68% HPD credible-region boundaries (somewhere close to +/-1.0):
    >>> print(np.amin(xpdf[pdf>HPDmin]), np.amax(xpdf[pdf>HPDmin]))

    >>> # Re-compute HPD for the 95% (withour recomputing the PDF):
    >>> pdf, xpdf, HPDmin = ms.cred_region(pdf=pdf, xpdf=xpdf, quantile=0.9545)
    >>> print(np.amin(xpdf[pdf>HPDmin]), np.amax(xpdf[pdf>HPDmin]))
    """
    if percentile is not None:
        with mu.Log() as log:
            log.warning('percentile is deprecated, use quantile instead.')
        quantile = percentile

    if pdf is None and xpdf is None:
        # Thin if posterior has too many samples (> 120k):
        thinning = np.amax([1, int(np.size(posterior)/120000)])
        # Compute the posterior's PDF:
        kernel = ss.gaussian_kde(posterior[::thinning])
        # Remove outliers:
        mean = np.mean(posterior)
        std  = np.std(posterior)
        k = 6
        lo = np.amax([mean-k*std, np.amin(posterior)])
        hi = np.amin([mean+k*std, np.amax(posterior)])
        # Use a Gaussian kernel density estimate to trace the PDF:
        x  = np.linspace(lo, hi, 100)
github pcubillos / mc3 / mc3 / sampler_driver.py View on Github external
>>>     sampler='dynesty', pstep=pstep, ncpu=ncpu, pmin=pmin, pmax=pmax,
  >>>     prior=prior, priorlow=priorlow, priorup=priorup,
  >>>     leastsq='lm', plots=True)

  >>> # See more examples and details at:
  >>> # https://mc3.readthedocs.io/en/latest/mcmc_tutorial.html
  >>> # https://mc3.readthedocs.io/en/latest/ns_tutorial.html
  """
  # Logging object:
  if isinstance(log, str):
      log = mu.Log(log, append=resume)
      closelog = True
  else:
      closelog = False
      if log is None:
          log = mu.Log()

  log.msg("\n{:s}\n"
      "  Multi-core Markov-chain Monte Carlo (MC3).\n"
      "  Version {}.\n"
      "  Copyright (c) 2015-{:d} Patricio Cubillos and collaborators.\n"
      "  MC3 is open-source software under the MIT license (see LICENSE).\n"
      "{:s}\n\n".format(log.sep, __version__, date.today().year, log.sep))

  # Deprecation warnings (to be removed not before summer 2020):
  if parname is not None:
      log.warning("parname argument is deprecated. Use pnames instead.")
      if pnames is None:
          pnames = parname
  if nproc is not None:
      log.warning("nproc argument is deprecated. Use ncpu instead.")
      if ncpu is None: