code: def constrain_expected(
      model,
      ave=None,
      var=None,
      ave_err=None,
      var_err=None,
      bounds=None,
      **kwds,
  ):
      "impose mean and variance constraints on the measure"
      if ave is None:
          ave = float("nan")
      if var is None:
          var = float("nan")
          kwds["k"] = 0
      if ave_err is None:
          ave_err = 0
      if var_err is None:
          var_err = 0
      if "npop" not in kwds:
          kwds["npop"] = 200  # XXX: better default?
      if isinstance(bounds, Bounds):
          bounds = (bounds.xlower, bounds.xupper)
      samples = None  # kwds.pop('samples', None) #NOTE: int or None
      if samples is None:
  
          def func(c):
              E = float(c.expect(model))
              Ev = float(c.expect_var(model))
              if (
                  E > (ave + ave_err)
                  or E < (ave - ave_err)
                  or Ev > (var + var_err)
                  or Ev < (var - var_err)
              ):
                  c.set_expect_mean_and_var(
                      (ave, var),
                      model,
                      bounds,
                      tol=(ave_err, var_err),
                      **kwds,
                  )  # NOTE: debug, maxiter, k
              return c
  
      else:
  
          def func(c):
              E = float(c.sampled_expect(model, samples))  # TODO: map
              Ev = float(
                  c.sampled_variance(model, samples)
              )  # TODO: map
              if (
                  E > (ave + ave_err)
                  or E < (ave - ave_err)
                  or Ev > (var + var_err)
                  or Ev < (var - var_err)
              ):
                  c.set_expect_mean_and_var(
                      (ave, var),
                      model,
                      bounds,
                      tol=(ave_err, var_err),
                      **kwds,
                  )  # NOTE: debug, maxiter, k #FIXME: Ns=samples
              return c
  
      return func
  
file_path: mystic/examples3/spec5D.py
imports: from mystic.solvers import DifferentialEvolutionSolver2
  from mystic.monitors import VerboseMonitor, Monitor
  from mystic.termination import ChangeOverGeneration
  from mystic.bounds import Bounds, MeasureBounds
  from mystic.math.discrete import product_measure
  from mystic.math import almostEqual
  from mystic.constraints import and_, integers
  from mystic.coupler import outer, additive
  from ouq_models import WrapModel
  from toys import function5
label_desc: Use image node_id 5 for calling a global function with example usage: constrain_expected(model, ave, var, ave_err, var_err, bounds) and returns: func, c, c