def runTest(dom, n=1, a=0, b=0): print("================== TEST : n= %s a=%s b=%s ================" % (n, a, b)) DIM = dom.getDim() normal = dom.getNormal() mypde = LinearPDE(dom, numEquations=n, numSolutions=n) x = dom.getX() A = mypde.createCoefficient("A") D = mypde.createCoefficient("D") Y = mypde.createCoefficient("Y") y = mypde.createCoefficient("y") q = mypde.createCoefficient("q") if n == 1: u_ref = Scalar(0., Solution(dom)) for j in range(DIM): q += whereZero(x[j]) A[j, j] = 1 y += sin(sqrt(2.)) * normal[0] Y += b * x[0] * sin(sqrt(2.)) D += b u_ref = x[0] * sin(sqrt(2.)) else: u_ref = Data(0., (n, ), Solution(dom)) for i in range(n): for j in range(DIM): q[i] += whereZero(x[j]) A[i, j, i, j] = 1 if j == i % DIM: y[i] += sin(i + sqrt(2.)) * normal[j] for j in range(n): if i == j: D[i, i] = b + (n - 1) * a Y[i] += b * x[i % DIM] * sin(i + sqrt(2.)) else: D[i, j] = -a Y[i] += a * (x[i % DIM] * sin(i + sqrt(2.)) - x[j % DIM] * sin(j + sqrt(2.))) u_ref[i] = x[i % DIM] * sin(i + sqrt(2.)) # - u_{j,ii} + b*u_i+ a*sum_{k<>j} (u_i-u_k) = F_j mypde.setValue(A=A, D=D, y=y, q=q, r=u_ref, Y=Y) mypde.getSolverOptions().setVerbosityOn() mypde.getSolverOptions().setTolerance(TOL) mypde.setSymmetryOn() u = mypde.getSolution() error = Lsup(u - u_ref) / Lsup(u_ref) print("error = ", error) if error > 10 * TOL: print( "XXXXXXXXXX Error to large ! XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
def setUpPDE(self): """ Return the underlying PDE. :rtype: `LinearPDE` """ if self.__pde is None: dom=self.__domain x = dom.getX() DIM=dom.getDim() q=whereZero(x[DIM-1]-inf(x[DIM-1])) for i in range(DIM-1): xi=x[i] q+=whereZero(xi-inf(xi))+whereZero(xi-sup(xi)) pde=LinearPDE(dom, numEquations=1) pde.getSolverOptions().setTolerance(self.__tol) pde.setSymmetryOn() A=pde.createCoefficient('A') X=pde.createCoefficient('X') pde.setValue(A=A, X=X, q=q) else: pde=self.__pde pde.resetRightHandSideCoefficients() return pde
def setUpPDE(self): """ Return the underlying PDE. :rtype: `LinearPDE` """ if self.__pde is None: dom = self.__domain x = dom.getX() DIM = dom.getDim() q = whereZero(x[DIM - 1] - inf(x[DIM - 1])) for i in range(DIM - 1): xi = x[i] q += whereZero(xi - inf(xi)) + whereZero(xi - sup(xi)) pde = LinearPDE(dom, numEquations=1) pde.getSolverOptions().setTolerance(self.__tol) pde.setSymmetryOn() A = pde.createCoefficient('A') X = pde.createCoefficient('X') pde.setValue(A=A, X=X, q=q) else: pde = self.__pde pde.resetRightHandSideCoefficients() return pde
def setUpPDE(self): """ Creates and returns the underlying PDE. :rtype: `LinearPDE` """ if self.__pde is None: if not HAVE_DIRECT: raise ValueError("Either this build of escript or the current MPI configuration does not support direct solvers.") pde=LinearPDE(self.__domain, numEquations=2) D=pde.createCoefficient('D') A=pde.createCoefficient('A') A[0,:,0,:]=kronecker(self.__domain.getDim()) A[1,:,1,:]=kronecker(self.__domain.getDim()) pde.setValue(A=A, D=D) if self.__fixAtBottom: DIM=self.__domain.getDim() z = self.__domain.getX()[DIM-1] pde.setValue(q=whereZero(z-self.__BX[DIM-1][0])*[1,1]) pde.getSolverOptions().setSolverMethod(SolverOptions.DIRECT) pde.getSolverOptions().setTolerance(self.__tol) pde.setSymmetryOff() else: pde=self.__pde pde.resetRightHandSideCoefficients() return pde
def runTest(dom, n=1, a=0, b=0): print("================== TEST : n= %s a=%s b=%s ================"%(n,a,b)) DIM=dom.getDim() normal=dom.getNormal() mypde=LinearPDE(dom, numEquations=n, numSolutions=n) x=dom.getX() A=mypde.createCoefficient("A") D=mypde.createCoefficient("D") Y=mypde.createCoefficient("Y") y=mypde.createCoefficient("y") q=mypde.createCoefficient("q") if n==1: u_ref=Scalar(0.,Solution(dom)) for j in range(DIM): q+=whereZero(x[j]) A[j,j]=1 y+=sin(sqrt(2.))*normal[0] Y+=b*x[0]*sin(sqrt(2.)) D+=b u_ref=x[0]*sin(sqrt(2.)) else: u_ref=Data(0.,(n,),Solution(dom)) for i in range(n): for j in range(DIM): q[i]+=whereZero(x[j]) A[i,j,i,j]=1 if j == i%DIM: y[i]+=sin(i+sqrt(2.))*normal[j] for j in range(n): if i==j: D[i,i]=b+(n-1)*a Y[i]+=b*x[i%DIM]*sin(i+sqrt(2.)) else: D[i,j]=-a Y[i]+=a*(x[i%DIM]*sin(i+sqrt(2.))-x[j%DIM]*sin(j+sqrt(2.))) u_ref[i]=x[i%DIM]*sin(i+sqrt(2.)) # - u_{j,ii} + b*u_i+ a*sum_{k<>j} (u_i-u_k) = F_j mypde.setValue(A=A, D=D, y=y, q=q, r=u_ref, Y=Y) mypde.getSolverOptions().setVerbosityOn() mypde.getSolverOptions().setTolerance(TOL) mypde.setSymmetryOn() u=mypde.getSolution() error=Lsup(u-u_ref)/Lsup(u_ref) print("error = ",error) if error > 10*TOL: print("XXXXXXXXXX Error to large ! XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
class SplitRegularization(CostFunction): """ The regularization term for the level set function ``m`` within the cost function J for an inversion: *J(m)=1/2 * sum_k integrate( mu[k] * ( w0[k] * m_k**2 * w1[k,i] * m_{k,i}**2) + sum_l<k mu_c[l,k] wc[l,k] * | curl(m_k) x curl(m_l) |^2* where w0[k], w1[k,i] and wc[k,l] are non-negative weighting factors and mu[k] and mu_c[l,k] are trade-off factors which may be altered during the inversion. The weighting factors are normalized such that their integrals over the domain are constant: *integrate(w0[k] + inner(w1[k,:],1/L[:]**2))=scale[k]* volume(domain)* *integrate(wc[l,k]*1/L**4)=scale_c[k]* volume(domain) * """ def __init__( self, domain, numLevelSets=1, w0=None, w1=None, wc=None, location_of_set_m=Data(), useDiagonalHessianApproximation=False, tol=1e-8, coordinates=None, scale=None, scale_c=None, ): """ initialization. :param domain: domain :type domain: `Domain` :param numLevelSets: number of level sets :type numLevelSets: ``int`` :param w0: weighting factor for the m**2 term. If not set zero is assumed. :type w0: ``Scalar`` if ``numLevelSets`` == 1 or `Data` object of shape (``numLevelSets`` ,) if ``numLevelSets`` > 1 :param w1: weighting factor for the grad(m_i) terms. If not set zero is assumed :type w1: ``Vector`` if ``numLevelSets`` == 1 or `Data` object of shape (``numLevelSets`` , DIM) if ``numLevelSets`` > 1 :param wc: weighting factor for the cross gradient terms. If not set zero is assumed. Used for the case if ``numLevelSets`` > 1 only. Only values ``wc[l,k]`` in the lower triangle (l<k) are used. :type wc: `Data` object of shape (``numLevelSets`` , ``numLevelSets``) :param location_of_set_m: marks location of zero values of the level set function ``m`` by a positive entry. :type location_of_set_m: ``Scalar`` if ``numLevelSets`` == 1 or `Data` object of shape (``numLevelSets`` ,) if ``numLevelSets`` > 1 :param useDiagonalHessianApproximation: if True cross gradient terms between level set components are ignored when calculating approximations of the inverse of the Hessian Operator. This can speed-up the calculation of the inverse but may lead to an increase of the number of iteration steps in the inversion. :type useDiagonalHessianApproximation: ``bool`` :param tol: tolerance when solving the PDE for the inverse of the Hessian Operator :type tol: positive ``float`` :param coordinates: defines coordinate system to be used :type coordinates: ReferenceSystem` or `SpatialCoordinateTransformation` :param scale: weighting factor for level set function variation terms. If not set one is used. :type scale: ``Scalar`` if ``numLevelSets`` == 1 or `Data` object of shape (``numLevelSets`` ,) if ``numLevelSets`` > 1 :param scale_c: scale for the cross gradient terms. If not set one is assumed. Used for the case if ``numLevelSets`` > 1 only. Only values ``scale_c[l,k]`` in the lower triangle (l<k) are used. :type scale_c: `Data` object of shape (``numLevelSets``,``numLevelSets``) """ if w0 is None and w1 is None: raise ValueError("Values for w0 or for w1 must be given.") if wc is None and numLevelSets > 1: raise ValueError("Values for wc must be given.") self.__pre_input = None self.__pre_args = None self.logger = logging.getLogger("inv.%s" % self.__class__.__name__) self.__domain = domain DIM = self.__domain.getDim() self.__numLevelSets = numLevelSets self.__trafo = makeTransformation(domain, coordinates) self.__pde = LinearPDE(self.__domain, numEquations=self.__numLevelSets, numSolutions=self.__numLevelSets) self.__pde.getSolverOptions().setTolerance(tol) self.__pde.setSymmetryOn() self.__pde.setValue(A=self.__pde.createCoefficient("A"), D=self.__pde.createCoefficient("D")) try: self.__pde.setValue(q=location_of_set_m) except IllegalCoefficientValue: raise ValueError("Unable to set location of fixed level set function.") # =========== check the shape of the scales: ======================== if scale is None: if numLevelSets == 1: scale = 1.0 else: scale = np.ones((numLevelSets,)) else: scale = np.asarray(scale) if numLevelSets == 1: if scale.shape == (): if not scale > 0: raise ValueError("Value for scale must be positive.") else: raise ValueError("Unexpected shape %s for scale." % scale.shape) else: if scale.shape is (numLevelSets,): if not min(scale) > 0: raise ValueError("All values for scale must be positive.") else: raise ValueError("Unexpected shape %s for scale." % scale.shape) if scale_c is None or numLevelSets < 2: scale_c = np.ones((numLevelSets, numLevelSets)) else: scale_c = np.asarray(scale_c) if scale_c.shape == (numLevelSets, numLevelSets): if not all([[scale_c[l, k] > 0.0 for l in range(k)] for k in range(1, numLevelSets)]): raise ValueError("All values in the lower triangle of scale_c must be positive.") else: raise ValueError("Unexpected shape %s for scale." % scale_c.shape) # ===== check the shape of the weights: ============================= if w0 is not None: w0 = interpolate(w0, self.__pde.getFunctionSpaceForCoefficient("D")) s0 = w0.getShape() if numLevelSets == 1: if not s0 == (): raise ValueError("Unexpected shape %s for weight w0." % (s0,)) else: if not s0 == (numLevelSets,): raise ValueError("Unexpected shape %s for weight w0." % (s0,)) if not self.__trafo.isCartesian(): w0 *= self.__trafo.getVolumeFactor() if not w1 is None: w1 = interpolate(w1, self.__pde.getFunctionSpaceForCoefficient("A")) s1 = w1.getShape() if numLevelSets == 1: if not s1 == (DIM,): raise ValueError("Unexpected shape %s for weight w1." % (s1,)) else: if not s1 == (numLevelSets, DIM): raise ValueError("Unexpected shape %s for weight w1." % (s1,)) if not self.__trafo.isCartesian(): f = self.__trafo.getScalingFactors() ** 2 * self.__trafo.getVolumeFactor() if numLevelSets == 1: w1 *= f else: for i in range(numLevelSets): w1[i, :] *= f if numLevelSets == 1: wc = None else: wc = interpolate(wc, self.__pde.getFunctionSpaceForCoefficient("A")) sc = wc.getShape() if not sc == (numLevelSets, numLevelSets): raise ValueError("Unexpected shape %s for weight wc." % (sc,)) if not self.__trafo.isCartesian(): raise ValueError("Non-cartesian coordinates for cross-gradient term is not supported yet.") # ============= now we rescale weights: ============================= L2s = np.asarray(boundingBoxEdgeLengths(domain)) ** 2 L4 = 1 / np.sum(1 / L2s) ** 2 if numLevelSets == 1: A = 0 if w0 is not None: A = integrate(w0) if w1 is not None: A += integrate(inner(w1, 1 / L2s)) if A > 0: f = scale / A if w0 is not None: w0 *= f if w1 is not None: w1 *= f else: raise ValueError("Non-positive weighting factor detected.") else: # numLevelSets > 1 for k in range(numLevelSets): A = 0 if w0 is not None: A = integrate(w0[k]) if w1 is not None: A += integrate(inner(w1[k, :], 1 / L2s)) if A > 0: f = scale[k] / A if w0 is not None: w0[k] *= f if w1 is not None: w1[k, :] *= f else: raise ValueError("Non-positive weighting factor for level set component %d detected." % k) # and now the cross-gradient: if wc is not None: for l in range(k): A = integrate(wc[l, k]) / L4 if A > 0: f = scale_c[l, k] / A wc[l, k] *= f # else: # raise ValueError("Non-positive weighting factor for cross-gradient level set components %d and %d detected."%(l,k)) self.__w0 = w0 self.__w1 = w1 self.__wc = wc self.__pde_is_set = False if self.__numLevelSets > 1: self.__useDiagonalHessianApproximation = useDiagonalHessianApproximation else: self.__useDiagonalHessianApproximation = True self._update_Hessian = True self.__num_tradeoff_factors = numLevelSets + ((numLevelSets - 1) * numLevelSets) // 2 self.setTradeOffFactors() self.__vol_d = vol(self.__domain) def getDomain(self): """ returns the domain of the regularization term :rtype: ``Domain`` """ return self.__domain def getCoordinateTransformation(self): """ returns the coordinate transformation being used :rtype: `CoordinateTransformation` """ return self.__trafo def getNumLevelSets(self): """ returns the number of level set functions :rtype: ``int`` """ return self.__numLevelSets def getPDE(self): """ returns the linear PDE to be solved for the Hessian Operator inverse :rtype: `LinearPDE` """ return self.__pde def getDualProduct(self, m, r): """ returns the dual product of a gradient represented by X=r[1] and Y=r[0] with a level set function m: *Y_i*m_i + X_ij*m_{i,j}* :type m: `Data` :type r: `ArithmeticTuple` :rtype: ``float`` """ A = 0 if not r[0].isEmpty(): A += integrate(inner(r[0], m)) if not r[1].isEmpty(): A += integrate(inner(r[1], grad(m))) return A def getNumTradeOffFactors(self): """ returns the number of trade-off factors being used. :rtype: ``int`` """ return self.__num_tradeoff_factors def setTradeOffFactors(self, mu=None): """ sets the trade-off factors for the level-set variation and the cross-gradient. :param mu: new values for the trade-off factors where values mu[:numLevelSets] are the trade-off factors for the level-set variation and the remaining values for the cross-gradient part with mu_c[l,k]=mu[numLevelSets+l+((k-1)*k)/2] (l<k). If no values for mu are given ones are used. Values must be positive. :type mu: ``list`` of ``float`` or ```numpy.array``` """ numLS = self.getNumLevelSets() numTF = self.getNumTradeOffFactors() if mu is None: mu = np.ones((numTF,)) else: mu = np.asarray(mu) if mu.shape == (numTF,): self.setTradeOffFactorsForVariation(mu[:numLS]) mu_c2 = np.zeros((numLS, numLS)) for k in range(numLS): for l in range(k): mu_c2[l, k] = mu[numLS + l + ((k - 1) * k) // 2] self.setTradeOffFactorsForCrossGradient(mu_c2) elif mu.shape == () and numLS == 1: self.setTradeOffFactorsForVariation(mu) else: raise ValueError("Unexpected shape %s for mu." % (mu.shape,)) def setTradeOffFactorsForVariation(self, mu=None): """ sets the trade-off factors for the level-set variation part. :param mu: new values for the trade-off factors. Values must be positive. :type mu: ``float``, ``list`` of ``float`` or ```numpy.array``` """ numLS = self.getNumLevelSets() if mu is None: if numLS == 1: mu = 1.0 else: mu = np.ones((numLS,)) if type(mu) == list: # this is a fix for older versions of numpy where passing in an a list of ints causes # this code to break. mu = np.asarray([float(i) for i in mu]) else: mu = np.asarray(mu) if numLS == 1: if mu.shape == (1,): mu = mu[0] if mu.shape == (): if mu > 0: self.__mu = mu self._new_mu = True else: raise ValueError("Value for trade-off factor must be positive.") else: raise ValueError("Unexpected shape %s for mu." % str(mu.shape)) else: if mu.shape == (numLS,): if min(mu) > 0: self.__mu = mu self._new_mu = True else: raise ValueError("All values for mu must be positive.") else: raise ValueError("Unexpected shape %s for trade-off factor." % str(mu.shape)) def setTradeOffFactorsForCrossGradient(self, mu_c=None): """ sets the trade-off factors for the cross-gradient terms. :param mu_c: new values for the trade-off factors for the cross-gradient terms. Values must be positive. If no value is given ones are used. Only value mu_c[l,k] for l<k are used. :type mu_c: ``float``, ``list`` of ``float`` or ``numpy.array`` """ numLS = self.getNumLevelSets() if mu_c is None or numLS < 2: self.__mu_c = np.ones((numLS, numLS)) elif isinstance(mu_c, float) or isinstance(mu_c, int): self.__mu_c = np.zeros((numLS, numLS)) self.__mu_c[:, :] = mu_c else: mu_c = np.asarray(mu_c) if mu_c.shape == (numLS, numLS): if not all([[mu_c[l, k] > 0.0 for l in range(k)] for k in range(1, numLS)]): raise ValueError("All trade-off factors in the lower triangle of mu_c must be positive.") else: self.__mu_c = mu_c self._new_mu = True else: raise ValueError("Unexpected shape %s for mu." % (mu_c.shape,)) def getArguments(self, m): """ """ raise RuntimeError("Please use the setPoint interface") self.__pre_args = grad(m) self.__pre_input = m return (self.__pre_args,) def getValueAtPoint(self): """ returns the value of the cost function J with respect to m. This equation is specified in the inversion cookbook. :rtype: ``float`` """ m = self.__pre_input grad_m = self.__pre_args mu = self.__mu mu_c = self.__mu_c DIM = self.getDomain().getDim() numLS = self.getNumLevelSets() A = 0 if self.__w0 is not None: r = inner(integrate(m ** 2 * self.__w0), mu) self.logger.debug("J_R[m^2] = %e" % r) A += r if self.__w1 is not None: if numLS == 1: r = integrate(inner(grad_m ** 2, self.__w1)) * mu self.logger.debug("J_R[grad(m)] = %e" % r) A += r else: for k in range(numLS): r = mu[k] * integrate(inner(grad_m[k, :] ** 2, self.__w1[k, :])) self.logger.debug("J_R[grad(m)][%d] = %e" % (k, r)) A += r if numLS > 1: for k in range(numLS): gk = grad_m[k, :] len_gk = length(gk) for l in range(k): gl = grad_m[l, :] r = mu_c[l, k] * integrate(self.__wc[l, k] * ((len_gk * length(gl)) ** 2 - inner(gk, gl) ** 2)) self.logger.debug("J_R[cross][%d,%d] = %e" % (l, k, r)) A += r return A / 2 def getValue(self, m, grad_m): """ returns the value of the cost function J with respect to m. This equation is specified in the inversion cookbook. :rtype: ``float`` """ if m != self.__pre_input: raise RuntimeError("Attempt to change point using getValue") # substituting cached values m = self.__pre_input grad_m = self.__pre_args mu = self.__mu mu_c = self.__mu_c DIM = self.getDomain().getDim() numLS = self.getNumLevelSets() A = 0 if self.__w0 is not None: r = inner(integrate(m ** 2 * self.__w0), mu) self.logger.debug("J_R[m^2] = %e" % r) A += r if self.__w1 is not None: if numLS == 1: r = integrate(inner(grad_m ** 2, self.__w1)) * mu self.logger.debug("J_R[grad(m)] = %e" % r) A += r else: for k in range(numLS): r = mu[k] * integrate(inner(grad_m[k, :] ** 2, self.__w1[k, :])) self.logger.debug("J_R[grad(m)][%d] = %e" % (k, r)) A += r if numLS > 1: for k in range(numLS): gk = grad_m[k, :] len_gk = length(gk) for l in range(k): gl = grad_m[l, :] r = mu_c[l, k] * integrate(self.__wc[l, k] * ((len_gk * length(gl)) ** 2 - inner(gk, gl) ** 2)) self.logger.debug("J_R[cross][%d,%d] = %e" % (l, k, r)) A += r return A / 2 def getGradient(self): raise RuntimeError("Split versions do not support getGradient. Use getGradientAtPoint instead.") def getGradientAtPoint(self): """ returns the gradient of the cost function J with respect to m. :note: This implementation returns Y_k=dPsi/dm_k and X_kj=dPsi/dm_kj """ # Using cached values m = self.__pre_input grad_m = self.__pre_args mu = self.__mu mu_c = self.__mu_c DIM = self.getDomain().getDim() numLS = self.getNumLevelSets() grad_m = grad(m, Function(m.getDomain())) if self.__w0 is not None: Y = m * self.__w0 * mu else: if numLS == 1: Y = Scalar(0, grad_m.getFunctionSpace()) else: Y = Data(0, (numLS,), grad_m.getFunctionSpace()) if self.__w1 is not None: if numLS == 1: X = grad_m * self.__w1 * mu else: X = grad_m * self.__w1 for k in range(numLS): X[k, :] *= mu[k] else: X = Data(0, grad_m.getShape(), grad_m.getFunctionSpace()) # cross gradient terms: if numLS > 1: for k in range(numLS): grad_m_k = grad_m[k, :] l2_grad_m_k = length(grad_m_k) ** 2 for l in range(k): grad_m_l = grad_m[l, :] l2_grad_m_l = length(grad_m_l) ** 2 grad_m_lk = inner(grad_m_l, grad_m_k) f = mu_c[l, k] * self.__wc[l, k] X[l, :] += f * (l2_grad_m_k * grad_m_l - grad_m_lk * grad_m_k) X[k, :] += f * (l2_grad_m_l * grad_m_k - grad_m_lk * grad_m_l) return ArithmeticTuple(Y, X) def getInverseHessianApproximationAtPoint(self, r, solve=True): """ """ # substituting cached values m = self.__pre_input grad_m = self.__pre_args if self._new_mu or self._update_Hessian: self._new_mu = False self._update_Hessian = False mu = self.__mu mu_c = self.__mu_c DIM = self.getDomain().getDim() numLS = self.getNumLevelSets() if self.__w0 is not None: if numLS == 1: D = self.__w0 * mu else: D = self.getPDE().getCoefficient("D") D.setToZero() for k in range(numLS): D[k, k] = self.__w0[k] * mu[k] self.getPDE().setValue(D=D) A = self.getPDE().getCoefficient("A") A.setToZero() if self.__w1 is not None: if numLS == 1: for i in range(DIM): A[i, i] = self.__w1[i] * mu else: for k in range(numLS): for i in range(DIM): A[k, i, k, i] = self.__w1[k, i] * mu[k] if numLS > 1: # this could be make faster by creating caches for grad_m_k, l2_grad_m_k and o_kk for k in range(numLS): grad_m_k = grad_m[k, :] l2_grad_m_k = length(grad_m_k) ** 2 o_kk = outer(grad_m_k, grad_m_k) for l in range(k): grad_m_l = grad_m[l, :] l2_grad_m_l = length(grad_m_l) ** 2 i_lk = inner(grad_m_l, grad_m_k) o_lk = outer(grad_m_l, grad_m_k) o_kl = outer(grad_m_k, grad_m_l) o_ll = outer(grad_m_l, grad_m_l) f = mu_c[l, k] * self.__wc[l, k] Z = f * (2 * o_lk - o_kl - i_lk * kronecker(DIM)) A[l, :, l, :] += f * (l2_grad_m_k * kronecker(DIM) - o_kk) A[l, :, k, :] += Z A[k, :, l, :] += transpose(Z) A[k, :, k, :] += f * (l2_grad_m_l * kronecker(DIM) - o_ll) self.getPDE().setValue(A=A) # self.getPDE().resetRightHandSideCoefficients() # self.getPDE().setValue(X=r[1]) # print "X only: ",self.getPDE().getSolution() # self.getPDE().resetRightHandSideCoefficients() # self.getPDE().setValue(Y=r[0]) # print "Y only: ",self.getPDE().getSolution() self.getPDE().resetRightHandSideCoefficients() self.getPDE().setValue(X=r[1], Y=r[0]) if not solve: return self.getPDE() return self.getPDE().getSolution() def updateHessian(self): """ notifies the class to recalculate the Hessian operator. """ if not self.__useDiagonalHessianApproximation: self._update_Hessian = True def getNorm(self, m): """ returns the norm of ``m``. :param m: level set function :type m: `Data` :rtype: ``float`` """ return sqrt(integrate(length(m) ** 2) / self.__vol_d) def setPoint(self, m): """ sets the point which this function will work with :param m: level set function :type m: `Data` """ self.__pre_input = m self.__pre_args = grad(m)
class PorosityOneHalfModel(DualPorosity): """ Model for gas and water in double prosity model tracking water and gas pressure in the fractured rock and gas concentration in the coal matrix. This corresponds to the coal bed methan model in the ECLIPSE code. """ def __init__(self, domain, phi_f=None, phi=None, L_g=None, perm_f_0=None, perm_f_1=None, perm_f_2=None, k_w =None, k_g=None, mu_w =None, mu_g =None, rho_w =None, rho_g=None, sigma=0, A_mg=0, f_rg=1., wells=[], g=9.81*U.m/U.sec**2): """ set up :param domain: domain :type domain: `esys.escript.Domain` :param phi_f: porosity of the fractured rock as function of the gas pressure :type phi_f: `MaterialPropertyWithDifferential` :param phi: total porosity if None phi=1. :type phi: scalar or None :param L_g: gas adsorption as function of gas pressure :type L_g: `MaterialPropertyWithDifferential` :param S_fg: gas saturation in the fractured rock as function of the capillary pressure p_fc=S_fg- p_f :type S_fg: `MaterialPropertyWithDifferential` :param perm_f_0: permeability in the x_0 direction in the fractured media :type perm_f_0: scalar :param perm_f_1: permeability in the x_1 direction in the fractured media :type perm_f_1: scalar :param perm_f_2: permeability in the x_2 direction in the fractured media :type perm_f_2: scalar :param k_w: relative permeability of water as function of water saturation :type k_w: `MaterialProperty` :param k_g: relative permeability of gas as function of gas saturation :type k_g: `MaterialProperty` :param mu_w: viscosity of water as function of water pressure :type mu_w: `MaterialProperty` :param mu_g: viscosity of gas as function of gas pressure :type mu_g: `MaterialProperty` :param rho_w: density of water as function of water pressure :type rho_w: `MaterialPropertyWithDifferential` :param rho_g: density of gas as function of gas pressure :type rho_g: `MaterialPropertyWithDifferential` :param wells : list of wells :type wells: list of `Well` :param sigma: shape factor for gas matrix diffusion :param A_mg: diffusion constant for gas adsorption :param f_rg: gas re-adsorption factor """ DualPorosity.__init__(self, domain, phi_f=phi_f, phi_m=None, phi=phi, S_fg=None, S_mg=None, perm_f_0=perm_f_0, perm_f_1=perm_f_1, perm_f_2=perm_f_2, perm_m_0=None , perm_m_1=None, perm_m_2=None, k_w =k_w, k_g=k_g, mu_w =mu_w, mu_g =mu_g, rho_w =rho_w, rho_g=rho_g, wells=wells, g=g) self.L_g=L_g self.sigma = sigma self.A_mg = A_mg self.f_rg = f_rg self.__pde=LinearPDE(self.domain, numEquations=3, numSolutions =3) def getPDEOptions(self): """ returns the `SolverOptions` of the underlying PDE """ return self.__pde.getSolverOptions() def getState(self): return self.u def getOldState(self): return self.u_old def setInitialState(self, p_top=1.*U.atm, p_bottom= 1.*U.atm, S_fg=0, c_mg=None): """ sets the initial state :param p: pressure :param S_fg: gas saturation in fractured rock :param c_mg: gas concentration in coal matrix at standart conditions. if not given it is calculated using the gas adsorption curve. """ if self.domain.getDim() == 2: p_init=Scalar((p_top + p_bottom) /2, Solution(self.domain)) else: z=self.u.getDomain().getX()[0] z_top=sup(z) z_bottom=inf(z) p_init=(p_bottom-p_top)/(z_bottom-z_top)*(z-z_top) + p_top S_fg_init=Scalar(S_fg, Solution(self.domain)) if c_mg == None: c_mg_init=self.L_g(p_init) else: c_mg_init=Scalar(c_mg, Solution(self.domain)) q_gas=Scalar(0., DiracDeltaFunctions(self.domain)) q_water=Scalar(0., DiracDeltaFunctions(self.domain)) BHP=interpolate(p_init, DiracDeltaFunctions(self.domain)) self.u=(p_init,S_fg_init, c_mg_init, BHP, q_gas, q_water) def solvePDE(self, dt): p_f, S_fg, c_mg, BHP_old, q_gas_old, q_water_old =self.getState() p_f_old, S_fg_old, c_mg_old, BHP, q_gas, q_water =self.getOldState() S_fw=1-S_fg if self.verbose: print("p_f range = ",inf(p_f),sup(p_f)) print("S_fg range = ",inf(S_fg),sup(S_fg)) print("S_fw range = ",inf(S_fw),sup(S_fw)) print("c_mg range = ",inf(c_mg),sup(c_mg)) print("BHP =",BHP) print("q_gas =",q_gas) print("q_water =",q_water) k_fw=self.k_w(S_fw) if self.verbose: print("k_fw range = ",inf(k_fw),sup(k_fw)) k_fg=self.k_g(S_fg) if self.verbose: print("k_fg range = ",inf(k_fg),sup(k_fg)) mu_fw=self.mu_w(p_f) if self.verbose: print("mu_fw range = ",inf(mu_fw),sup(mu_fw)) mu_fg=self.mu_g(p_f) if self.verbose: print("mu_fg range = ",inf(mu_fg),sup(mu_fg)) phi_f =self.phi_f.getValue(p_f) dphi_fdp=self.phi_f.getValueDifferential(p_f) if self.verbose: print("phi_f range = ",inf(phi_f),sup(phi_f)," (slope %e,%e)"%(inf(dphi_fdp), sup(dphi_fdp))) rho_fw = self.rho_w.getValue(p_f) drho_fwdp = self.rho_w.getValueDifferential(p_f) if self.verbose: print("rho_fw range = ",inf(rho_fw),sup(rho_fw)," (slope %e,%e)"%(inf(drho_fwdp), sup(drho_fwdp))) rho_fg = self.rho_g.getValue(p_f) rho_g_surf = self.rho_g.rho_surf drho_fgdp = self.rho_g.getValueDifferential(p_f) if self.verbose: print("rho_fg range = ",inf(rho_fg),sup(rho_fg)," (slope %e,%e)"%(inf(drho_fgdp), sup(drho_fgdp))) print("rho_fg surf = ",rho_g_surf) L_g = self.L_g(p_f) dL_gdp = self.L_g.getValueDifferential(p_f) if self.verbose: print("L_g range = ",inf(L_g),sup(L_g)," (slope %e,%e)"%(inf(dL_gdp), sup(dL_gdp))) A_fw = rho_fw * k_fw/mu_fw A_fg = rho_fg * k_fg/mu_fg m = whereNegative(L_g - c_mg) H = self.sigma * self.A_mg * (m + (1-m) * self.f_rg * S_fg ) E_fpp= S_fw * ( rho_fw * dphi_fdp + phi_f * drho_fwdp ) E_fps= - phi_f * rho_fw E_fsp= S_fg * ( rho_fg * dphi_fdp + phi_f * drho_fgdp ) E_fss= phi_f * rho_fg F_fw=0. F_fg=0. D_fw=0. D_fg=0. prod_index=Scalar(0., DiracDeltaFunctions(self.domain)) geo_fac=Scalar(0., DiracDeltaFunctions(self.domain)) for I in self.wells: prod_index.setTaggedValue(I.name, I.getProductivityIndex() ) geo_fac.setTaggedValue(I.name, I.geo_fac) F_fp_Y = A_fw * prod_index * BHP * geo_fac F_fs_Y = A_fg * prod_index * BHP * geo_fac D_fpp = A_fw * prod_index * geo_fac D_fsp = A_fg * prod_index * geo_fac if self.domain.getDim() == 3: F_fp_X = ( A_fw * self.g * rho_fw * self.perm_f[2] ) * kronecker(self.domain)[2] F_fs_X = ( A_fg * self.g * rho_fg * self.perm_f[2] ) * kronecker(self.domain)[2] else: F_fp_X = 0 * kronecker(self.domain)[1] F_fs_X = 0 * kronecker(self.domain)[1] F_mg_Y = H * L_g D=self.__pde.createCoefficient("D") A=self.__pde.createCoefficient("A") Y=self.__pde.createCoefficient("Y") X=self.__pde.createCoefficient("X") d_dirac=self.__pde.createCoefficient("d_dirac") y_dirac=self.__pde.createCoefficient("y_dirac") D[0,0]=E_fpp D[0,1]=E_fps d_dirac[0,0]=dt * D_fpp D[1,0]=E_fsp D[1,1]=E_fss D[1,2]= rho_g_surf d_dirac[1,0]=dt * D_fsp D[0,2]= -dt * H * dL_gdp * 0 D[2,2]= 1 + dt * H for i in range(self.domain.getDim()): A[0,i,0,i] = dt * A_fw * self.perm_f[i] A[1,i,1,i] = dt * A_fg * self.perm_f[i] X[0,:]= dt * F_fp_X X[1,:]= dt * F_fs_X Y[0] = E_fpp * p_f_old + E_fps * S_fg_old Y[1] = E_fsp * p_f_old + E_fss * S_fg_old + rho_g_surf * c_mg_old Y[2] = c_mg_old + dt * ( F_mg_Y - H * dL_gdp * p_f *0 ) y_dirac[0] =dt * F_fp_Y y_dirac[1] =dt * F_fs_Y print("HHH D[0,0] = ",D[0,0]) print("HHH D[0,1] = ",D[0,1]) print("HHH D[0,2] = ",D[0,2]) print("HHH D[1,0] = ",D[1,0]) print("HHH D[1,1] = ",D[1,1]) print("HHH D[1,2] = ",D[1,2]) print("HHH D[2,0] = ",D[2,0]) print("HHH D[2,1] = ",D[2,1]) print("HHH D[2,2] = ",D[2,2]) print("HHH A_fw = ",A_fw) print("HHH A_fg = ",A_fg) print("HHH A[0,0,0,0] = ",A[0,0,0,0]) print("HHH A[0,1,0,1] = ",A[0,1,0,1]) print("HHH A[1,0,1,0] = ",A[1,0,1,0]) print("HHH A[1,1,1,1] = ",A[1,1,1,1]) print("HHH Y[0] ",Y[0]) print("HHH Y[1] ",Y[1]) print("HHH Y[2] ",Y[2]) print("HHH F_fp_Y ",F_fp_Y) print("HHH F_fs_Y ",F_fs_Y) print("HHH F_mg_Y ",F_mg_Y) print("HHH H = ",H) self.__pde.setValue(A=A, D=D, X=X, Y=Y, d_dirac=d_dirac , y_dirac=y_dirac) u2 = self.__pde.getSolution() # this is deals with round-off errors to maintain physical meaningful values # we should do this in a better way to detect values that are totally wrong p_f=u2[0] S_fg=clip(u2[1],minval=0, maxval=1) c_mg=clip(u2[2],minval=0) q=Scalar(0., DiracDeltaFunctions(self.domain)) BHP_limit=Scalar(0., DiracDeltaFunctions(self.domain)) water_well_mask=Scalar(0., DiracDeltaFunctions(self.domain)) for I in self.wells: q.setTaggedValue(I.name, I.getFlowRate(self.t+dt)) BHP_limit.setTaggedValue(I.name, I.getBHPLimit()) if I.getPhase() == Well.WATER: water_well_mask.setTaggedValue(I.name, 1) p_f_wells=interpolate(p_f, DiracDeltaFunctions(self.domain)) S_fg_wells=interpolate(S_fg, DiracDeltaFunctions(self.domain)) A_fw_wells= self.k_w(1-S_fg_wells)/self.mu_w(p_f_wells)*self.rho_w(p_f_wells) A_fg_wells= self.k_g(S_fg_wells)/self.mu_g(p_f_wells)*self.rho_g(p_f_wells) BHP=clip( p_f_wells - q/prod_index * ( m * self.rho_w.rho_surf/A_fw_wells + (1-m)* self.rho_g.rho_surf/A_fg_wells ), minval = BHP_limit) BHP=clip( p_f_wells - q/prod_index * self.rho_w.rho_surf/A_fw_wells, minval = BHP_limit) q_gas = prod_index * A_fg_wells * (p_f_wells - BHP)/self.rho_g.rho_surf q_water = prod_index * A_fw_wells * (p_f_wells - BHP)/self.rho_w.rho_surf return (p_f,S_fg, c_mg, BHP, q_gas, q_water )
class Regularization(CostFunction): """ The regularization term for the level set function ``m`` within the cost function J for an inversion: *J(m)=1/2 * sum_k integrate( mu[k] * ( w0[k] * m_k**2 * w1[k,i] * m_{k,i}**2) + sum_l<k mu_c[l,k] wc[l,k] * | curl(m_k) x curl(m_l) |^2* where w0[k], w1[k,i] and wc[k,l] are non-negative weighting factors and mu[k] and mu_c[l,k] are trade-off factors which may be altered during the inversion. The weighting factors are normalized such that their integrals over the domain are constant: *integrate(w0[k] + inner(w1[k,:],1/L[:]**2))=scale[k]* volume(domain)* *integrate(wc[l,k]*1/L**4)=scale_c[k]* volume(domain) * """ def __init__(self, domain, numLevelSets=1, w0=None, w1=None, wc=None, location_of_set_m=Data(), useDiagonalHessianApproximation=False, tol=1e-8, coordinates=None, scale=None, scale_c=None): """ initialization. :param domain: domain :type domain: `Domain` :param numLevelSets: number of level sets :type numLevelSets: ``int`` :param w0: weighting factor for the m**2 term. If not set zero is assumed. :type w0: ``Scalar`` if ``numLevelSets`` == 1 or `Data` object of shape (``numLevelSets`` ,) if ``numLevelSets`` > 1 :param w1: weighting factor for the grad(m_i) terms. If not set zero is assumed :type w1: ``Vector`` if ``numLevelSets`` == 1 or `Data` object of shape (``numLevelSets`` , DIM) if ``numLevelSets`` > 1 :param wc: weighting factor for the cross gradient terms. If not set zero is assumed. Used for the case if ``numLevelSets`` > 1 only. Only values ``wc[l,k]`` in the lower triangle (l<k) are used. :type wc: `Data` object of shape (``numLevelSets`` , ``numLevelSets``) :param location_of_set_m: marks location of zero values of the level set function ``m`` by a positive entry. :type location_of_set_m: ``Scalar`` if ``numLevelSets`` == 1 or `Data` object of shape (``numLevelSets`` ,) if ``numLevelSets`` > 1 :param useDiagonalHessianApproximation: if True cross gradient terms between level set components are ignored when calculating approximations of the inverse of the Hessian Operator. This can speed-up the calculation of the inverse but may lead to an increase of the number of iteration steps in the inversion. :type useDiagonalHessianApproximation: ``bool`` :param tol: tolerance when solving the PDE for the inverse of the Hessian Operator :type tol: positive ``float`` :param coordinates: defines coordinate system to be used :type coordinates: ReferenceSystem` or `SpatialCoordinateTransformation` :param scale: weighting factor for level set function variation terms. If not set one is used. :type scale: ``Scalar`` if ``numLevelSets`` == 1 or `Data` object of shape (``numLevelSets`` ,) if ``numLevelSets`` > 1 :param scale_c: scale for the cross gradient terms. If not set one is assumed. Used for the case if ``numLevelSets`` > 1 only. Only values ``scale_c[l,k]`` in the lower triangle (l<k) are used. :type scale_c: `Data` object of shape (``numLevelSets``,``numLevelSets``) """ if w0 is None and w1 is None: raise ValueError("Values for w0 or for w1 must be given.") if wc is None and numLevelSets > 1: raise ValueError("Values for wc must be given.") self.logger = logging.getLogger('inv.%s' % self.__class__.__name__) self.__domain = domain DIM = self.__domain.getDim() self.__numLevelSets = numLevelSets self.__trafo = makeTransformation(domain, coordinates) self.__pde = LinearPDE(self.__domain, numEquations=self.__numLevelSets, numSolutions=self.__numLevelSets) self.__pde.getSolverOptions().setTolerance(tol) self.__pde.setSymmetryOn() self.__pde.setValue( A=self.__pde.createCoefficient('A'), D=self.__pde.createCoefficient('D'), ) try: self.__pde.setValue(q=location_of_set_m) except IllegalCoefficientValue: raise ValueError( "Unable to set location of fixed level set function.") # =========== check the shape of the scales: ======================== if scale is None: if numLevelSets == 1: scale = 1. else: scale = np.ones((numLevelSets, )) else: scale = np.asarray(scale) if numLevelSets == 1: if scale.shape == (): if not scale > 0: raise ValueError("Value for scale must be positive.") else: raise ValueError("Unexpected shape %s for scale." % scale.shape) else: if scale.shape is (numLevelSets, ): if not min(scale) > 0: raise ValueError( "All values for scale must be positive.") else: raise ValueError("Unexpected shape %s for scale." % scale.shape) if scale_c is None or numLevelSets < 2: scale_c = np.ones((numLevelSets, numLevelSets)) else: scale_c = np.asarray(scale_c) if scale_c.shape == (numLevelSets, numLevelSets): if not all([[scale_c[l, k] > 0. for l in range(k)] for k in range(1, numLevelSets)]): raise ValueError( "All values in the lower triangle of scale_c must be positive." ) else: raise ValueError("Unexpected shape %s for scale." % scale_c.shape) # ===== check the shape of the weights: ============================= if w0 is not None: w0 = interpolate(w0, self.__pde.getFunctionSpaceForCoefficient('D')) s0 = w0.getShape() if numLevelSets == 1: if not s0 == (): raise ValueError("Unexpected shape %s for weight w0." % (s0, )) else: if not s0 == (numLevelSets, ): raise ValueError("Unexpected shape %s for weight w0." % (s0, )) if not self.__trafo.isCartesian(): w0 *= self.__trafo.getVolumeFactor() if not w1 is None: w1 = interpolate(w1, self.__pde.getFunctionSpaceForCoefficient('A')) s1 = w1.getShape() if numLevelSets == 1: if not s1 == (DIM, ): raise ValueError("Unexpected shape %s for weight w1." % (s1, )) else: if not s1 == (numLevelSets, DIM): raise ValueError("Unexpected shape %s for weight w1." % (s1, )) if not self.__trafo.isCartesian(): f = self.__trafo.getScalingFactors( )**2 * self.__trafo.getVolumeFactor() if numLevelSets == 1: w1 *= f else: for i in range(numLevelSets): w1[i, :] *= f if numLevelSets == 1: wc = None else: wc = interpolate(wc, self.__pde.getFunctionSpaceForCoefficient('A')) sc = wc.getShape() if not sc == (numLevelSets, numLevelSets): raise ValueError("Unexpected shape %s for weight wc." % (sc, )) if not self.__trafo.isCartesian(): raise ValueError( "Non-cartesian coordinates for cross-gradient term is not supported yet." ) # ============= now we rescale weights: ============================= L2s = np.asarray(boundingBoxEdgeLengths(domain))**2 L4 = 1 / np.sum(1 / L2s)**2 if numLevelSets == 1: A = 0 if w0 is not None: A = integrate(w0) if w1 is not None: A += integrate(inner(w1, 1 / L2s)) if A > 0: f = scale / A if w0 is not None: w0 *= f if w1 is not None: w1 *= f else: raise ValueError("Non-positive weighting factor detected.") else: # numLevelSets > 1 for k in range(numLevelSets): A = 0 if w0 is not None: A = integrate(w0[k]) if w1 is not None: A += integrate(inner(w1[k, :], 1 / L2s)) if A > 0: f = scale[k] / A if w0 is not None: w0[k] *= f if w1 is not None: w1[k, :] *= f else: raise ValueError( "Non-positive weighting factor for level set component %d detected." % k) # and now the cross-gradient: if wc is not None: for l in range(k): A = integrate(wc[l, k]) / L4 if A > 0: f = scale_c[l, k] / A wc[l, k] *= f # else: # raise ValueError("Non-positive weighting factor for cross-gradient level set components %d and %d detected."%(l,k)) self.__w0 = w0 self.__w1 = w1 self.__wc = wc self.__pde_is_set = False if self.__numLevelSets > 1: self.__useDiagonalHessianApproximation = useDiagonalHessianApproximation else: self.__useDiagonalHessianApproximation = True self._update_Hessian = True self.__num_tradeoff_factors = numLevelSets + ( (numLevelSets - 1) * numLevelSets) // 2 self.setTradeOffFactors() self.__vol_d = vol(self.__domain) def getDomain(self): """ returns the domain of the regularization term :rtype: ``Domain`` """ return self.__domain def getCoordinateTransformation(self): """ returns the coordinate transformation being used :rtype: `CoordinateTransformation` """ return self.__trafo def getNumLevelSets(self): """ returns the number of level set functions :rtype: ``int`` """ return self.__numLevelSets def getPDE(self): """ returns the linear PDE to be solved for the Hessian Operator inverse :rtype: `LinearPDE` """ return self.__pde def getDualProduct(self, m, r): """ returns the dual product of a gradient represented by X=r[1] and Y=r[0] with a level set function m: *Y_i*m_i + X_ij*m_{i,j}* :type m: `Data` :type r: `ArithmeticTuple` :rtype: ``float`` """ A = 0 if not r[0].isEmpty(): A += integrate(inner(r[0], m)) if not r[1].isEmpty(): A += integrate(inner(r[1], grad(m))) return A def getNumTradeOffFactors(self): """ returns the number of trade-off factors being used. :rtype: ``int`` """ return self.__num_tradeoff_factors def setTradeOffFactors(self, mu=None): """ sets the trade-off factors for the level-set variation and the cross-gradient. :param mu: new values for the trade-off factors where values mu[:numLevelSets] are the trade-off factors for the level-set variation and the remaining values for the cross-gradient part with mu_c[l,k]=mu[numLevelSets+l+((k-1)*k)/2] (l<k). If no values for mu are given ones are used. Values must be positive. :type mu: ``list`` of ``float`` or ```numpy.array``` """ numLS = self.getNumLevelSets() numTF = self.getNumTradeOffFactors() if mu is None: mu = np.ones((numTF, )) else: mu = np.asarray(mu) if mu.shape == (numTF, ): self.setTradeOffFactorsForVariation(mu[:numLS]) mu_c2 = np.zeros((numLS, numLS)) for k in range(numLS): for l in range(k): mu_c2[l, k] = mu[numLS + l + ((k - 1) * k) // 2] self.setTradeOffFactorsForCrossGradient(mu_c2) elif mu.shape == () and numLS == 1: self.setTradeOffFactorsForVariation(mu) else: raise ValueError("Unexpected shape %s for mu." % (mu.shape, )) def setTradeOffFactorsForVariation(self, mu=None): """ sets the trade-off factors for the level-set variation part. :param mu: new values for the trade-off factors. Values must be positive. :type mu: ``float``, ``list`` of ``float`` or ```numpy.array``` """ numLS = self.getNumLevelSets() if mu is None: if numLS == 1: mu = 1. else: mu = np.ones((numLS, )) if type(mu) == list: #this is a fix for older versions of numpy where passing in an a list of ints causes #this code to break. mu = np.asarray([float(i) for i in mu]) else: mu = np.asarray(mu) if numLS == 1: if mu.shape == (1, ): mu = mu[0] if mu.shape == (): if mu > 0: self.__mu = mu self._new_mu = True else: raise ValueError( "Value for trade-off factor must be positive.") else: raise ValueError("Unexpected shape %s for mu." % str(mu.shape)) else: if mu.shape == (numLS, ): if min(mu) > 0: self.__mu = mu self._new_mu = True else: raise ValueError("All values for mu must be positive.") else: raise ValueError("Unexpected shape %s for trade-off factor." % str(mu.shape)) def setTradeOffFactorsForCrossGradient(self, mu_c=None): """ sets the trade-off factors for the cross-gradient terms. :param mu_c: new values for the trade-off factors for the cross-gradient terms. Values must be positive. If no value is given ones are used. Only value mu_c[l,k] for l<k are used. :type mu_c: ``float``, ``list`` of ``float`` or ``numpy.array`` """ numLS = self.getNumLevelSets() if mu_c is None or numLS < 2: self.__mu_c = np.ones((numLS, numLS)) elif isinstance(mu_c, float) or isinstance(mu_c, int): self.__mu_c = np.zeros((numLS, numLS)) self.__mu_c[:, :] = mu_c else: mu_c = np.asarray(mu_c) if mu_c.shape == (numLS, numLS): if not all([[mu_c[l, k] > 0. for l in range(k)] for k in range(1, numLS)]): raise ValueError( "All trade-off factors in the lower triangle of mu_c must be positive." ) else: self.__mu_c = mu_c self._new_mu = True else: raise ValueError("Unexpected shape %s for mu." % (mu_c.shape, )) def getArguments(self, m): """ """ return grad(m), def getValue(self, m, grad_m): """ returns the value of the cost function J with respect to m. This equation is specified in the inversion cookbook. :rtype: ``float`` """ mu = self.__mu mu_c = self.__mu_c DIM = self.getDomain().getDim() numLS = self.getNumLevelSets() A = 0 if self.__w0 is not None: r = inner(integrate(m**2 * self.__w0), mu) self.logger.debug("J_R[m^2] = %e" % r) A += r if self.__w1 is not None: if numLS == 1: r = integrate(inner(grad_m**2, self.__w1)) * mu self.logger.debug("J_R[grad(m)] = %e" % r) A += r else: for k in range(numLS): r = mu[k] * integrate( inner(grad_m[k, :]**2, self.__w1[k, :])) self.logger.debug("J_R[grad(m)][%d] = %e" % (k, r)) A += r if numLS > 1: for k in range(numLS): gk = grad_m[k, :] len_gk = length(gk) for l in range(k): gl = grad_m[l, :] r = mu_c[l, k] * integrate(self.__wc[l, k] * ( (len_gk * length(gl))**2 - inner(gk, gl)**2)) self.logger.debug("J_R[cross][%d,%d] = %e" % (l, k, r)) A += r return A / 2 def getGradient(self, m, grad_m): """ returns the gradient of the cost function J with respect to m. :note: This implementation returns Y_k=dPsi/dm_k and X_kj=dPsi/dm_kj """ mu = self.__mu mu_c = self.__mu_c DIM = self.getDomain().getDim() numLS = self.getNumLevelSets() grad_m = grad(m, Function(m.getDomain())) if self.__w0 is not None: Y = m * self.__w0 * mu else: if numLS == 1: Y = Scalar(0, grad_m.getFunctionSpace()) else: Y = Data(0, (numLS, ), grad_m.getFunctionSpace()) if self.__w1 is not None: if numLS == 1: X = grad_m * self.__w1 * mu else: X = grad_m * self.__w1 for k in range(numLS): X[k, :] *= mu[k] else: X = Data(0, grad_m.getShape(), grad_m.getFunctionSpace()) # cross gradient terms: if numLS > 1: for k in range(numLS): grad_m_k = grad_m[k, :] l2_grad_m_k = length(grad_m_k)**2 for l in range(k): grad_m_l = grad_m[l, :] l2_grad_m_l = length(grad_m_l)**2 grad_m_lk = inner(grad_m_l, grad_m_k) f = mu_c[l, k] * self.__wc[l, k] X[l, :] += f * (l2_grad_m_k * grad_m_l - grad_m_lk * grad_m_k) X[k, :] += f * (l2_grad_m_l * grad_m_k - grad_m_lk * grad_m_l) return ArithmeticTuple(Y, X) def getInverseHessianApproximation(self, m, r, grad_m, solve=True): """ """ if self._new_mu or self._update_Hessian: self._new_mu = False self._update_Hessian = False mu = self.__mu mu_c = self.__mu_c DIM = self.getDomain().getDim() numLS = self.getNumLevelSets() if self.__w0 is not None: if numLS == 1: D = self.__w0 * mu else: D = self.getPDE().getCoefficient("D") D.setToZero() for k in range(numLS): D[k, k] = self.__w0[k] * mu[k] self.getPDE().setValue(D=D) A = self.getPDE().getCoefficient("A") A.setToZero() if self.__w1 is not None: if numLS == 1: for i in range(DIM): A[i, i] = self.__w1[i] * mu else: for k in range(numLS): for i in range(DIM): A[k, i, k, i] = self.__w1[k, i] * mu[k] if numLS > 1: # this could be make faster by creating caches for grad_m_k, l2_grad_m_k and o_kk for k in range(numLS): grad_m_k = grad_m[k, :] l2_grad_m_k = length(grad_m_k)**2 o_kk = outer(grad_m_k, grad_m_k) for l in range(k): grad_m_l = grad_m[l, :] l2_grad_m_l = length(grad_m_l)**2 i_lk = inner(grad_m_l, grad_m_k) o_lk = outer(grad_m_l, grad_m_k) o_kl = outer(grad_m_k, grad_m_l) o_ll = outer(grad_m_l, grad_m_l) f = mu_c[l, k] * self.__wc[l, k] Z = f * (2 * o_lk - o_kl - i_lk * kronecker(DIM)) A[l, :, l, :] += f * (l2_grad_m_k * kronecker(DIM) - o_kk) A[l, :, k, :] += Z A[k, :, l, :] += transpose(Z) A[k, :, k, :] += f * (l2_grad_m_l * kronecker(DIM) - o_ll) self.getPDE().setValue(A=A) #self.getPDE().resetRightHandSideCoefficients() #self.getPDE().setValue(X=r[1]) #print "X only: ",self.getPDE().getSolution() #self.getPDE().resetRightHandSideCoefficients() #self.getPDE().setValue(Y=r[0]) #print "Y only: ",self.getPDE().getSolution() self.getPDE().resetRightHandSideCoefficients() self.getPDE().setValue(X=r[1], Y=r[0]) if not solve: return self.getPDE() oldsettings = self.getPDE().getSolverOptions().getSolverMethod() self.getPDE().getSolverOptions().setSolverMethod(SolverOptions.GMRES) solution = self.getPDE().getSolution() self.getPDE().getSolverOptions().setSolverMethod(oldsettings) return solution def updateHessian(self): """ notifies the class to recalculate the Hessian operator. """ if not self.__useDiagonalHessianApproximation: self._update_Hessian = True def getNorm(self, m): """ returns the norm of ``m``. :param m: level set function :type m: `Data` :rtype: ``float`` """ return sqrt(integrate(length(m)**2) / self.__vol_d)