Exemplo n.º 1
0
    def cost(rv):
        c = product_measure().load(rv, npts)
        #XXX: apply 'filters' to catch errors in constraints solver (necessary ?)
        ##################### begin function-specific #####################
        E = float(c.expect(model))
        if E > (target[0] + error[0]) or E < (target[0] - error[0]):
            if debug: print("skipping expect: %s" % E)
            return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS

#   E = float(c[0].var)  # var(h)
#   if E > (target[1] + error[1]) or E < (target[1] - error[1]):
#     if debug: print("skipping variance: %s" % E)
#     return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS

        E = float(c[0].mean)  # mean(h)
        if E > (target[2] + error[2]) or E < (target[2] - error[2]):
            if debug: print("skipping expect: %s" % E)
            return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS

        E = float(c[2].mean)  # mean(v)
        if E > (target[3] + error[3]) or E < (target[3] - error[3]):
            if debug: print("skipping expect: %s" % E)
            return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS
        ###################### end function-specific ######################
        return MINMAX * c.pof(model)
Exemplo n.º 2
0
    def objective(self, rv, axis=None, iter=True):
        """calculate probability of failure for model, under uncertainty

    Input:
        rv: list of input parameters
        axis: int, the index of output to calculate (all, by default)
        iter: bool, if True, calculate per axis, else calculate for all axes

    Returns:
        the probability of failure for the specified axis (or all axes)

    NOTE:
        respects constraints on input parameters and product measure
        model is a function returning a boolean (True for success)

    NOTE:
        for product_measure, use sampled_pof(model) if samples, else pof(model)
        """
        # check constraints
        c = product_measure().load(rv, self.npts)
        if not self.cvalid(c) or not self.xvalid(rv):
            import numpy as np
            return np.inf
        # get probability of failure
        if iter and axis is None and self.axes is not None:
            model = (lambda x: self.model(x,axis=i) for i in range(self.axes))
            if self.samples is None:
                return tuple(c.pof(m) for m in model)
            # else use sampled support
            return tuple(c.sampled_pof(m, self.samples) for m in model)
        # else, get probability of failure for the given axis
        model = lambda x: self.model(x, axis=axis)
        if self.samples is None:
            return c.pof(model)
        return c.sampled_pof(model, self.samples)
Exemplo n.º 3
0
 def cost(rv):
     c = product_measure().load(rv, npts)
     E = float(c.expect(model))
     if E > (target[0] + error[0]) or E < (target[0] - error[0]):
         if debug: print("skipping expect: %s" % E)
         return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS
     return MINMAX * c.pof(model)
Exemplo n.º 4
0
    def objective(self, rv, axis=None):
        """calculate value at risk of model, under uncertainty

    Input:
        rv: list of input parameters
        axis: int, the index of output to calculate (all, by default)

    Returns:
        the value at risk for the specified axis

    NOTE:
        respects constraints on input parameters and product measure

    NOTE:
        for product_measure, use sampled_ptp if samples, else ess_ptp
        """
        # check constraints
        c = product_measure().load(rv, self.npts)
        if not self.cvalid(c) or not self.xvalid(rv):
            import numpy as np
            return np.inf
        # get value at risk
        if axis is None and self.axes is not None:
            model = (lambda x: self.model(x, axis=i) for i in range(self.axes))
            if self.samples is None:
                return tuple(c.ess_ptp(m) for m in model)
            # else use sampled support
            return tuple(c.sampled_ptp(m, self.samples) for m in model)
        # else, get value at risk for the given axis
        model = lambda x: self.model(x, axis=axis)
        if self.samples is None:
            from mystic.math.measures import ess_ptp #TODO: c.ess_ptp
            return ess_ptp(model, c.positions, c.weights)
        return c.sampled_ptp(model, self.samples)
Exemplo n.º 5
0
    def objective(self, rv, axis=None):
        """calculate expected value of model, under uncertainty

    Input:
        rv: list of input parameters
        axis: int, the index of output to calculate (all, by default)

    Returns:
        the expected value for the specified axis

    NOTE:
        respects constraints on input parameters and product measure

    NOTE:
        for product_measure, use sampled_expect if samples, else expect
        """
        # check constraints
        c = product_measure().load(rv, self.npts)
        if not self.cvalid(c) or not self.xvalid(rv):
            import numpy as np
            return np.inf
        # get expected value
        if axis is None and self.axes is not None:
            model = (lambda x: self.model(x, axis=i) for i in range(self.axes))
            if self.samples is None:
                return tuple(c.expect(m) for m in model)
            # else use sampled support
            return tuple(c.sampled_expect(m, self.samples) for m in model)
        # else, get expected value for the given axis
        model = lambda x: self.model(x, axis=axis)
        if self.samples is None:
            return c.expect(model)
        return c.sampled_expect(model, self.samples)
  def cost(rv):
    c = product_measure().load(rv, npts)
    #XXX: apply 'filters' to catch errors in constraints solver (necessary ?)
    ##################### begin function-specific #####################
    E = float(c.expect(model))
    if E > (target[0] + error[0]) or E < (target[0] - error[0]):
      if debug: print("skipping expect: %s" % E)
      return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS

#   E = float(c[0].var)  # var(h)
#   if E > (target[1] + error[1]) or E < (target[1] - error[1]):
#     if debug: print("skipping variance: %s" % E)
#     return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS

    E = float(c[0].mean)  # mean(h)
    if E > (target[2] + error[2]) or E < (target[2] - error[2]):
      if debug: print("skipping expect: %s" % E)
      return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS

    E = float(c[2].mean)  # mean(v)
    if E > (target[3] + error[3]) or E < (target[3] - error[3]):
      if debug: print("skipping expect: %s" % E)
      return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS
    ###################### end function-specific ######################
    return MINMAX * c.pof(model)
 def cost(rv):
   c = product_measure().load(rv, npts)
   E = float(c.expect(model))
   if E > (target[0] + error[0]) or E < (target[0] - error[0]):
     if debug: print("skipping expect: %s" % E)
     return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS
   return MINMAX * c.pof(model)
Exemplo n.º 8
0
 def func(x, *args, **kwds):
     # populate a product measure with params
     c = product_measure()
     c.load(x, npts)
     # apply all collapses
     for clps in tracking:
         for k,v in getattr(clps, 'iteritems', clps.items)():
             c[k].positions, c[k].weights = \
               impose_collapse(v, c[k].positions, c[k].weights)
     for clps in noweight:
         for k,v in getattr(clps, 'iteritems', clps.items)():
             c[k].positions, c[k].weights = \
               impose_unweighted(v, c[k].positions, c[k].weights, False)
     # convert to params and apply function
     return f(c.flatten(), *args, **kwds)
Exemplo n.º 9
0
 def func(x, *args, **kwds):
     # populate a product measure with params
     c = product_measure()
     c.load(x, npts)
     # apply all collapses
     for clps in tracking:
         for k, v in getattr(clps, 'iteritems', clps.items)():
             c[k].positions, c[k].weights = \
               impose_collapse(v, c[k].positions, c[k].weights)
     for clps in noweight:
         for k, v in getattr(clps, 'iteritems', clps.items)():
             c[k].positions, c[k].weights = \
               impose_unweighted(v, c[k].positions, c[k].weights, False)
     # convert to params and apply function
     return f(c.flatten(), *args, **kwds)
Exemplo n.º 10
0
 def constraints(rv):
   c = product_measure().load(rv, npts)
   # NOTE: bounds wi in [0,1] enforced by filtering
   # impose norm on each discrete measure
   for measure in c:
     if not almostEqual(float(measure.mass), 1.0, tol=atol, rel=rtol):
       measure.normalize()
   # impose expectation on product measure
   ##################### begin function-specific #####################
   E = float(c.expect(model))
   if not (E <= float(target[0] + error[0])) \
   or not (float(target[0] - error[0]) <= E):
     c.set_expect(target[0], model, (x_lb,x_ub), tol=error[0])
   ###################### end function-specific ######################
   # extract weights and positions
   return c.flatten()
Exemplo n.º 11
0
 def constraints(rv):
     c = product_measure().load(rv, npts)
     # NOTE: bounds wi in [0,1] enforced by filtering
     # impose norm on each discrete measure
     for measure in c:
         if not almostEqual(float(measure.mass), 1.0, tol=atol, rel=rtol):
             measure.normalize()
     # impose expectation on product measure
     ##################### begin function-specific #####################
     E = float(c.expect(model))
     if not (E <= float(target[0] + error[0])) \
     or not (float(target[0] - error[0]) <= E):
         c.set_expect(target[0], model, (x_lb, x_ub), tol=error[0])
     ###################### end function-specific ######################
     # extract weights and positions
     return c.flatten()
Exemplo n.º 12
0
    def objective(self, rv, axis=None, idx=0): #FIXME: idx != None, is fixed
        """calculate mean value of input, under uncertainty

    Input:
        rv: list of input parameters
        axis: int, the index of output to calculate (all, by default)
        idx: int, the index of input to calculate (all, by default) #FIXME

    Returns:
        the mean value for the specified index

    NOTE:
        respects constraints on input parameters and product measure

    NOTE:
        for product_measure, use sampled_expect if samples, else expect
        """
        # check constraints
        c = product_measure().load(rv, self.npts)
        if not self.cvalid(c) or not self.xvalid(rv): #FIXME: set model,samples in constraints
            import numpy as np
            return np.inf
        # get mean value
        if axis is None and self.axes is not None:
            model = (lambda x: self.model(x, axis=i) for i in range(self.axes))
            if self.samples is None:
                return NotImplemented #FIXME: set model,samples in constraints
            # else use sampled support
            return NotImplemented #FIXME: set model,samples in constraints
        # else, get mean value for the given axis
        if axis is None:
            model = lambda x: self.model(x)
        else:
            model = lambda x: self.model(x, axis=axis)
        if self.samples is None:
            if idx is None:
                res = (c[i].mean for i in self.nx)
                return tuple(res)
            return c[idx].mean #FIXME: set model,samples in constraints
        return NotImplemented #FIXME: set model,samples in constraints
Exemplo n.º 13
0
  for i in range(ny):
    param_string += "'wy%s', " % str(i+1)
  for i in range(ny):
    param_string += "'y%s', " % str(i+1)
  for i in range(nz):
    param_string += "'wz%s', " % str(i+1)
  for i in range(nz):
    param_string += "'z%s', " % str(i+1)
  param_string = param_string[:-2] + "]"

  print(" parameters: %s" % param_string)
  print(" lower bounds: %s" % lower_bounds)
  print(" upper bounds: %s" % upper_bounds)
# print(" ...")
  pars = (target,error)
  npts = (nx,ny,nz)
  bounds = (lower_bounds,upper_bounds)
  solved, diameter = maximize(pars,npts,bounds)

  from numpy import array
  from mystic.math.discrete import product_measure
  c = product_measure()
  c.load(solved,npts)
  print("solved: [wx,x]\n%s" % array(list(zip(c[0].weights,c[0].positions))))
  print("solved: [wy,y]\n%s" % array(list(zip(c[1].weights,c[1].positions))))
  print("solved: [wz,z]\n%s" % array(list(zip(c[2].weights,c[2].positions))))

  print("expect: %s" % str( c.expect(model) ))

# EOF
Exemplo n.º 14
0
    for i in range(ny):
        param_string += "'y%s', " % str(i + 1)
    for i in range(nz):
        param_string += "'wz%s', " % str(i + 1)
    for i in range(nz):
        param_string += "'z%s', " % str(i + 1)
    param_string = param_string[:-2] + "]"

    print(" parameters: %s" % param_string)
    print(" lower bounds: %s" % lower_bounds)
    print(" upper bounds: %s" % upper_bounds)
    # print(" ...")
    pars = (target, error)
    npts = (nx, ny, nz)
    bounds = (lower_bounds, upper_bounds)
    solved, diameter = maximize(pars, npts, bounds)

    from numpy import array
    from mystic.math.discrete import product_measure
    c = product_measure().load(solved, npts)
    print("solved: [wx,x]\n%s" %
          array(list(zip(c[0].weights, c[0].positions))))
    print("solved: [wy,y]\n%s" %
          array(list(zip(c[1].weights, c[1].positions))))
    print("solved: [wz,z]\n%s" %
          array(list(zip(c[2].weights, c[2].positions))))

    print("expect: %s" % str(c.expect(model)))

# EOF
    param_string += "'y%s', " % str(i+1)
  for i in range(nz):
    param_string += "'wz%s', " % str(i+1)
  for i in range(nz):
    param_string += "'z%s', " % str(i+1)
  param_string = param_string[:-2] + "]"

  print(" parameters: %s" % param_string)
  print(" lower bounds: %s" % lower_bounds)
  print(" upper bounds: %s" % upper_bounds)
# print(" ...")
  pars = (target,error)
  npts = (nx,ny,nz)
  bounds = (lower_bounds,upper_bounds)
  solved, diameter = maximize(pars,npts,bounds)

  from numpy import array
  from mystic.math.discrete import product_measure
  c = product_measure().load(solved,npts)
  print("solved: [wx,x]\n%s" % array(list(zip(c[0].weights,c[0].positions))))
  print("solved: [wy,y]\n%s" % array(list(zip(c[1].weights,c[1].positions))))
  print("solved: [wz,z]\n%s" % array(list(zip(c[2].weights,c[2].positions))))
 
  # XXX: 4D-expect
  print("expect: %s" % str( c.expect(model) ))
  print("var (x): %s" % str( c[0].var ))   # var(h)
  print("mean(x): %s" % str( c[0].mean ))  # mean(h)
  print("mean(z): %s" % str( c[2].mean ))  # mean(v)

# EOF
Exemplo n.º 16
0
 def func(rv):
     c = product_measure().load(rv, npts)
     c = f(c)
     return c.flatten()
Exemplo n.º 17
0
 def func(rv):
     c = product_measure().load(rv, npts)
     return f(c)
Exemplo n.º 18
0
    for i in range(nz):
        param_string += "'z%s', " % str(i + 1)
    param_string = param_string[:-2] + "]"

    print(" parameters: %s" % param_string)
    print(" lower bounds: %s" % lower_bounds)
    print(" upper bounds: %s" % upper_bounds)
    # print(" ...")
    pars = (target, error)
    npts = (nx, ny, nz)
    bounds = (lower_bounds, upper_bounds)
    solved, diameter = maximize(pars, npts, bounds)

    from numpy import array
    from mystic.math.discrete import product_measure
    c = product_measure()
    c.load(solved, npts)
    print("solved: [wx,x]\n%s" %
          array(list(zip(c[0].weights, c[0].positions))))
    print("solved: [wy,y]\n%s" %
          array(list(zip(c[1].weights, c[1].positions))))
    print("solved: [wz,z]\n%s" %
          array(list(zip(c[2].weights, c[2].positions))))

    # XXX: 4D-expect
    print("expect: %s" % str(c.expect(model)))
    print("var (x): %s" % str(c[0].var))  # var(h)
    print("mean(x): %s" % str(c[0].mean))  # mean(h)
    print("mean(z): %s" % str(c[2].mean))  # mean(v)

# EOF