preprocess.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import os
  2. import json
  3. import ast
  4. import operator as op
  5. import numpy as np
  6. from collections import namedtuple
  7. from scipy.linalg import block_diag
  8. # load the configuration file
  9. installDir = os.path.split(__file__)[0]
  10. cfgPath = os.path.join(installDir, "config")
  11. for loc in os.curdir, os.path.expanduser("~"), cfgPath:
  12. try:
  13. with open(os.path.join(loc, "config.json")) as source:
  14. configdata = json.load(source)
  15. except IOError:
  16. pass
  17. # evaluate the input json function with only these math operators
  18. operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
  19. ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
  20. ast.USub: op.neg}
  21. def eval_expr(expr):
  22. return eval_(ast.parse(expr, mode='eval').body)
  23. def eval_(node):
  24. if isinstance(node, ast.Num): # <number>
  25. return node.n
  26. elif isinstance(node, "x"):
  27. return node.n
  28. elif isinstance(node, ast.BinOp): # <left> <operator> <right>
  29. return operators[type(node.op)](eval_(node.left), eval_(node.right))
  30. elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
  31. return operators[type(node.op)](eval_(node.operand))
  32. else:
  33. raise TypeError(node)
  34. def queryYesNo(question, default="yes"):
  35. valid = {"yes": True, "y": True, "ye": True,
  36. "no": False, "n": False}
  37. if default is None:
  38. prompt = " [y/n] "
  39. elif default == "yes":
  40. prompt = " [Y/n] "
  41. elif default == "no":
  42. prompt = " [y/N] "
  43. else:
  44. raise ValueError("invalid default answer: '%s'" % default)
  45. while True:
  46. print(question + prompt, end='')
  47. choice = input().lower()
  48. if default is not None and choice == '':
  49. return valid[default]
  50. elif choice in valid:
  51. return valid[choice]
  52. else:
  53. print("Please respond with 'yes' or 'no' "
  54. "(or 'y' or 'n').\n")
  55. def setDefaultCoefficients():
  56. question = "Do you want to use the default parameters?"
  57. isDefault = queryYesNo(question, "yes")
  58. if (isDefault):
  59. diffDefault = configdata["coefficients"]["diffusion"]
  60. convDefault = configdata["coefficients"]["convection"]
  61. reactionDefault = configdata["coefficients"]["reaction"]
  62. pOrderDefault = configdata["coefficients"]["pOrder"]
  63. numEleDefault = configdata["coefficients"]["numEle"]
  64. tauPlusDefault = configdata["coefficients"]["tauPlus"]
  65. tauMinusDefault = configdata["coefficients"]["tauMinus"]
  66. coeff = coefficients(diffDefault, convDefault, reactionDefault,
  67. pOrderDefault, numEleDefault,
  68. tauPlusDefault, tauMinusDefault)
  69. else:
  70. coeff = coefficients.fromInput()
  71. return coeff
  72. def shape(x, p):
  73. """generate p shape functions and its first order derivative
  74. at the given location x. x can be an array"""
  75. A = np.array([np.linspace(-1, 1, p)]).T**np.arange(p)
  76. C = np.linalg.inv(A).T
  77. x = np.array([x]).T
  78. shp = C.dot((x**np.arange(p)).T)
  79. shpx = C[:, 1::1].dot((x**np.arange(p - 1) * np.arange(1, p)).T)
  80. return shp, shpx
  81. def forcing(x):
  82. f = np.zeros(len(x))
  83. for i, forcingItem in enumerate(x):
  84. forcingExpr = configdata["forcing"]
  85. # replace the 'x' in the json file with the function parameters
  86. f[i] = eval_expr(forcingExpr.replace("x", str(forcingItem)))
  87. return f
  88. def boundaryCondition(case):
  89. if case == 'primal':
  90. # primal problem
  91. bcLeft = configdata["boundary"]["left"]
  92. bcRight = configdata["boundary"]["right"]
  93. bc = [bcLeft, bcRight]
  94. if case == 'adjoint':
  95. # adjoint problem
  96. bc = [0, 1]
  97. return bc
  98. class coefficients:
  99. def __init__(self, diff, conv, reaction, pOrder, numEle, tauPlus, tauMinus):
  100. if diff == 0:
  101. # set the diffusion constant to a small number
  102. # to avoid division by zero error
  103. diff = 1e-16
  104. self.DIFFUSION = diff
  105. self.CONVECTION = conv
  106. self.REACTION = reaction
  107. self.pOrder = pOrder
  108. self.numEle = numEle
  109. self.TAUPLUS = tauPlus
  110. self.TAUMINUS = tauMinus
  111. @classmethod
  112. def fromInput(cls):
  113. while True:
  114. try:
  115. print("Please provide the following coefficients.")
  116. diff = float(input("Diffusion constant (float): "))
  117. conv = float(input("Covection constant (float): "))
  118. reaction = float(input("Reaction constant (float): "))
  119. pOrder = int(input("Order of polynomials (int): "))
  120. numEle = int(input("Number of elements (int): "))
  121. tauPlus = float(input("Stablization parameter plus (float): "))
  122. tauMinus = float(
  123. input("Stablization parameter minus (float): "))
  124. except ValueError:
  125. print("Sorry, wrong data type.")
  126. continue
  127. else:
  128. print("Something is wrong. Exit.")
  129. break
  130. return cls(diff, conv, reaction, pOrder, numEle, tauPlus, tauMinus)
  131. class discretization(object):
  132. """Given the problem statement and current mesh,
  133. construct the discretization matrices"""
  134. def __init__(self, coeff, mesh, enrich=None):
  135. self.mesh = mesh
  136. self.coeff = coeff
  137. self.enrich = enrich
  138. # the following init are for the sake of simplicity
  139. self.numBasisFuncs = coeff.pOrder + 1
  140. self.tau_pos = coeff.TAUPLUS
  141. self.tau_neg = coeff.TAUMINUS
  142. self.conv = coeff.CONVECTION
  143. self.kappa = coeff.DIFFUSION
  144. self.numEle = len(mesh) - 1
  145. self.dist = self.distGen()
  146. # shape function and gauss quadrature
  147. self.gqOrder = 5 * self.numBasisFuncs
  148. self.xi, self.wi = np.polynomial.legendre.leggauss(self.gqOrder)
  149. self.shp, self.shpx = shape(self.xi, self.numBasisFuncs)
  150. # enrich the space if the enrich argument is given
  151. if enrich is not None:
  152. self.shpEnrich, self.shpxEnrich = shape(
  153. self.xi, self.numBasisFuncs + enrich)
  154. def distGen(self):
  155. dist = np.zeros(self.numEle)
  156. for i in range(1, self.numEle + 1):
  157. dist[i - 1] = self.mesh[i] - self.mesh[i - 1]
  158. return dist
  159. def matGroup(self):
  160. lhsMat = self.lhsGen()
  161. F, L, R = lhsMat.F, lhsMat.L, lhsMat.R
  162. eleMat = self.eleGen()
  163. A, B, BonU, D = eleMat.A, eleMat.B, eleMat.BonU, eleMat.D
  164. faceMat = self.interfaceGen()
  165. C, E, G, H = faceMat.C, faceMat.E, faceMat.G, faceMat.H
  166. matGroup = namedtuple(
  167. 'matGroup', ['A', 'B', 'BonU', 'C', 'D', 'E', 'F', 'G', 'H', 'L', 'R'])
  168. return matGroup(A, B, BonU, C, D, E, F, G, H, L, R)
  169. def lhsGen(self):
  170. """Generate matrices associated with left hand side"""
  171. if self.enrich is not None:
  172. # when enrich is given
  173. # provide matrices used in the DWR residual calculation
  174. numBasisFuncs = self.numBasisFuncs + self.enrich
  175. shp = self.shpEnrich
  176. else:
  177. numBasisFuncs = self.numBasisFuncs
  178. shp = self.shp
  179. # forcing vector F
  180. F = np.zeros(numBasisFuncs * self.numEle)
  181. for i in range(1, self.numEle + 1):
  182. f = self.dist[i - 1] / 2 \
  183. * shp.dot(self.wi * forcing(self.mesh[i - 1] +
  184. 1 / 2 * (1 + self.xi) *
  185. self.dist[i - 1]))
  186. F[(i - 1) * numBasisFuncs:i * numBasisFuncs] = f
  187. F[0] += (self.conv + self.tau_pos) * boundaryCondition('primal')[0]
  188. F[-1] += (-self.conv + self.tau_neg) * boundaryCondition('primal')[1]
  189. # L, easy in 1d
  190. L = np.zeros(self.numEle - 1)
  191. # R, easy in 1d
  192. R = np.zeros(numBasisFuncs * self.numEle)
  193. R[0] = boundaryCondition('primal')[0]
  194. R[-1] = -boundaryCondition('primal')[1]
  195. lhsMat = namedtuple('lhsMat', ['F', 'L', 'R'])
  196. return lhsMat(F, L, R)
  197. def eleGen(self):
  198. """Generate matrices associated with elements"""
  199. if self.enrich is not None:
  200. numBasisFuncsEnrich = self.numBasisFuncs + self.enrich
  201. shpEnrich = self.shpEnrich
  202. shpxEnrich = self.shpxEnrich
  203. b = (self.shpx.T * np.ones((self.gqOrder, self.numBasisFuncs))
  204. ).T.dot(np.diag(self.wi).dot(shpEnrich.T))
  205. # BonQ is only used in calculating DWR residual
  206. BonQ = block_diag(*[b] * (self.numEle)).T
  207. else:
  208. numBasisFuncsEnrich = self.numBasisFuncs
  209. shpEnrich = self.shp
  210. shpxEnrich = self.shpx
  211. BonQ = None
  212. a = 1 / self.coeff.DIFFUSION * \
  213. shpEnrich.dot(np.diag(self.wi).dot(self.shp.T))
  214. A = np.repeat(self.dist, self.numBasisFuncs) / \
  215. 2 * block_diag(*[a] * (self.numEle))
  216. b = (shpxEnrich.T * np.ones((self.gqOrder, numBasisFuncsEnrich))
  217. ).T.dot(np.diag(self.wi).dot(self.shp.T))
  218. B = block_diag(*[b] * (self.numEle))
  219. d = self.coeff.REACTION * \
  220. shpEnrich.dot(np.diag(self.wi).dot(self.shp.T))
  221. # assemble D
  222. dFace = np.zeros((numBasisFuncsEnrich, self.numBasisFuncs))
  223. dFace[0, 0] = self.tau_pos
  224. dFace[-1, -1] = self.tau_neg
  225. dConv = -self.conv * (shpxEnrich.T * np.ones((self.gqOrder,
  226. numBasisFuncsEnrich)))\
  227. .T.dot(np.diag(self.wi).dot(self.shp.T))
  228. D = np.repeat(self.dist, self.numBasisFuncs) / 2 * \
  229. block_diag(*[d] * (self.numEle)) + \
  230. block_diag(*[dFace] * (self.numEle)) +\
  231. block_diag(*[dConv] * (self.numEle))
  232. eleMat = namedtuple('eleMat', ['A', 'B', 'BonU', 'D'])
  233. return eleMat(A, B, BonQ, D)
  234. def interfaceGen(self):
  235. """Generate matrices associated with interfaces"""
  236. if self.enrich is not None:
  237. # when enrich is given
  238. # provide matrices used in the DWR residual calculation
  239. numBasisFuncs = self.numBasisFuncs + self.enrich
  240. else:
  241. numBasisFuncs = self.numBasisFuncs
  242. tau_pos, tau_neg, conv = self.tau_pos, self.tau_neg, self.conv
  243. # elemental h
  244. h = np.zeros((2, 2))
  245. h[0, 0], h[-1, -1] = -conv - tau_pos, conv - tau_neg
  246. # mappinng matrix
  247. map_h = np.zeros((2, self.numEle), dtype=int)
  248. map_h[:, 0] = np.arange(2)
  249. for i in np.arange(1, self.numEle):
  250. map_h[:, i] = np.arange(
  251. map_h[2 - 1, i - 1], map_h[2 - 1, i - 1] + 2)
  252. # assemble H and eliminate boundaries
  253. H = np.zeros((self.numEle + 1, self.numEle + 1))
  254. for i in range(self.numEle):
  255. for j in range(2):
  256. m = map_h[j, i]
  257. for k in range(2):
  258. n = map_h[k, i]
  259. H[m, n] += h[j, k]
  260. H = H[1:self.numEle][:, 1:self.numEle]
  261. # elemental e
  262. e = np.zeros((numBasisFuncs, 2))
  263. e[0, 0], e[-1, -1] = -conv - tau_pos, conv - tau_neg
  264. # mapping matrix
  265. map_e_x = np.arange(numBasisFuncs * self.numEle,
  266. dtype=int).reshape(self.numEle,
  267. numBasisFuncs).T
  268. map_e_y = map_h
  269. # assemble global E
  270. E = np.zeros((numBasisFuncs * self.numEle, self.numEle + 1))
  271. for i in range(self.numEle):
  272. for j in range(numBasisFuncs):
  273. m = map_e_x[j, i]
  274. for k in range(2):
  275. n = map_e_y[k, i]
  276. E[m, n] += e[j, k]
  277. E = E[:, 1:self.numEle]
  278. # elemental c
  279. c = np.zeros((numBasisFuncs, 2))
  280. c[0, 0], c[-1, -1] = -1, 1
  281. # assemble global C
  282. C = np.zeros((numBasisFuncs * self.numEle, self.numEle + 1))
  283. for i in range(self.numEle):
  284. for j in range(numBasisFuncs):
  285. m = map_e_x[j, i]
  286. for k in range(2):
  287. n = map_e_y[k, i]
  288. C[m, n] += c[j, k]
  289. C = C[:, 1:self.numEle]
  290. # elemental g
  291. g = np.zeros((2, numBasisFuncs))
  292. g[0, 0], g[-1, -1] = tau_pos, tau_neg
  293. # mapping matrix
  294. map_g_x = map_h
  295. map_g_y = np.arange(numBasisFuncs * self.numEle,
  296. dtype=int).reshape(self.numEle,
  297. numBasisFuncs).T
  298. # assemble global G
  299. G = np.zeros((self.numEle + 1, numBasisFuncs * self.numEle))
  300. for i in range(self.numEle):
  301. for j in range(2):
  302. m = map_g_x[j, i]
  303. for k in range(numBasisFuncs):
  304. n = map_g_y[k, i]
  305. G[m, n] += g[j, k]
  306. G = G[1:self.numEle, :]
  307. faceMat = namedtuple('faceMat', ['C', 'E', 'G', 'H'])
  308. return faceMat(C, E, G, H)