geometry.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. '''
  2. This module contains subroutines concerning the geometry-improving of the interpolation set.
  3. Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
  4. Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
  5. Python translation by Nickolai Belakovski.
  6. '''
  7. from ..common.consts import DEBUGGING
  8. from ..common.linalg import isinv, matprod, inprod, norm, primasum, primapow2
  9. import numpy as np
  10. def setdrop_tr(ximproved, d, delta, rho, sim, simi):
  11. '''
  12. This function finds (the index) of a current interpolation point to be replaced with
  13. the trust-region trial point. See (19)-(22) of the COBYLA paper.
  14. N.B.:
  15. 1. If XIMPROVED == True, then JDROP > 0 so that D is included into XPT. Otherwise,
  16. it is a bug.
  17. 2. COBYLA never sets JDROP = NUM_VARS
  18. TODO: Check whether it improves the performance if JDROP = NUM_VARS is allowed when
  19. XIMPROVED is True. Note that UPDATEXFC should be revised accordingly.
  20. '''
  21. # Local variables
  22. itol = 0.1
  23. # Sizes
  24. num_vars = np.size(sim, 0)
  25. # Preconditions
  26. if DEBUGGING:
  27. assert num_vars >= 1
  28. assert np.size(d) == num_vars and all(np.isfinite(d))
  29. assert delta >= rho and rho > 0
  30. assert np.size(sim, 0) == num_vars and np.size(sim, 1) == num_vars + 1
  31. assert np.isfinite(sim).all()
  32. assert all(np.max(abs(sim[:, :num_vars]), axis=0) > 0)
  33. assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
  34. assert np.isfinite(simi).all()
  35. assert isinv(sim[:, :num_vars], simi, itol)
  36. #====================#
  37. # Calculation starts #
  38. #====================#
  39. # -------------------------------------------------------------------------------------------------- #
  40. # The following code is Powell's scheme for defining JDROP.
  41. # -------------------------------------------------------------------------------------------------- #
  42. # ! JDROP = 0 by default. It cannot be removed, as JDROP may not be set below in some cases (e.g.,
  43. # ! when XIMPROVED == FALSE, MAXVAL(ABS(SIMID)) <= 1, and MAXVAL(VETA) <= EDGMAX).
  44. # jdrop = 0
  45. #
  46. # ! SIMID(J) is the value of the J-th Lagrange function at D. It is the counterpart of VLAG in UOBYQA
  47. # ! and DEN in NEWUOA/BOBYQA/LINCOA, but it excludes the value of the (N+1)-th Lagrange function.
  48. # simid = matprod(simi, d)
  49. # if (any(abs(simid) > 1) .or. (ximproved .and. any(.not. is_nan(simid)))) then
  50. # jdrop = int(maxloc(abs(simid), mask=(.not. is_nan(simid)), dim=1), kind(jdrop))
  51. # !!MATLAB: [~, jdrop] = max(simid, [], 'omitnan');
  52. # end if
  53. #
  54. # ! VETA(J) is the distance from the J-th vertex of the simplex to the best vertex, taking the trial
  55. # ! point SIM(:, N+1) + D into account.
  56. # if (ximproved) then
  57. # veta = sqrt(sum((sim(:, 1:n) - spread(d, dim=2, ncopies=n))**2, dim=1))
  58. # !!MATLAB: veta = sqrt(sum((sim(:, 1:n) - d).^2)); % d should be a column! Implicit expansion
  59. # else
  60. # veta = sqrt(sum(sim(:, 1:n)**2, dim=1))
  61. # end if
  62. #
  63. # ! VSIG(J) (J=1, .., N) is the Euclidean distance from vertex J to the opposite face of the simplex.
  64. # vsig = ONE / sqrt(sum(simi**2, dim=2))
  65. # sigbar = abs(simid) * vsig
  66. #
  67. # ! The following JDROP will overwrite the previous one if its premise holds.
  68. # mask = (veta > factor_delta * delta .and. (sigbar >= factor_alpha * delta .or. sigbar >= vsig))
  69. # if (any(mask)) then
  70. # jdrop = int(maxloc(veta, mask=mask, dim=1), kind(jdrop))
  71. # !!MATLAB: etamax = max(veta(mask)); jdrop = find(mask & ~(veta < etamax), 1, 'first');
  72. # end if
  73. #
  74. # ! Powell's code does not include the following instructions. With Powell's code, if SIMID consists
  75. # ! of only NaN, then JDROP can be 0 even when XIMPROVED == TRUE (i.e., D reduces the merit function).
  76. # ! With the following code, JDROP cannot be 0 when XIMPROVED == TRUE, unless VETA is all NaN, which
  77. # ! should not happen if X0 does not contain NaN, the trust-region/geometry steps never contain NaN,
  78. # ! and we exit once encountering an iterate containing Inf (due to overflow).
  79. # if (ximproved .and. jdrop <= 0) then ! Write JDROP <= 0 instead of JDROP == 0 for robustness.
  80. # jdrop = int(maxloc(veta, mask=(.not. is_nan(veta)), dim=1), kind(jdrop))
  81. # !!MATLAB: [~, jdrop] = max(veta, [], 'omitnan');
  82. # end if
  83. # -------------------------------------------------------------------------------------------------- #
  84. # Powell's scheme ends here.
  85. # -------------------------------------------------------------------------------------------------- #
  86. # The following definition of JDROP is inspired by SETDROP_TR in UOBYQA/NEWUOA/BOBYQA/LINCOA.
  87. # It is simpler and works better than Powell's scheme. Note that we allow JDROP to be NUM_VARS+1 if
  88. # XIMPROVED is True, whereas Powell's code does not.
  89. # See also (4.1) of Scheinberg-Toint-2010: Self-Correcting Geometry in Model-Based Algorithms for
  90. # Derivative-Free Unconstrained Optimization, which refers to the strategy here as the "combined
  91. # distance/poisedness criteria".
  92. # DISTSQ[j] is the square of the distance from the jth vertex of the simplex to get "best" point so
  93. # far, taking the trial point SIM[:, NUM_VARS] + D into account.
  94. distsq = np.zeros(np.size(sim, 1))
  95. if ximproved:
  96. distsq[:num_vars] = primasum(primapow2(sim[:, :num_vars] - np.tile(d, (num_vars, 1)).T), axis=0)
  97. distsq[num_vars] = primasum(d*d)
  98. else:
  99. distsq[:num_vars] = primasum(primapow2(sim[:, :num_vars]), axis=0)
  100. distsq[num_vars] = 0
  101. weight = np.maximum(1, distsq / primapow2(np.maximum(rho, delta/10))) # Similar to Powell's NEWUOA code.
  102. # Other possible definitions of weight. They work almost the same as the one above.
  103. # weight = distsq # Similar to Powell's LINCOA code, but WRONG. See comments in LINCOA/geometry.f90.
  104. # weight = max(1, max(25 * distsq / delta**2)) # Similar to Powell's BOBYQA code, works well.
  105. # weight = max(1, max(10 * distsq / delta**2))
  106. # weight = max(1, max(1e2 * distsq / delta**2))
  107. # weight = max(1, max(distsq / rho**2)) ! Similar to Powell's UOBYQA
  108. # If 0 <= j < NUM_VARS, SIMID[j] is the value of the jth Lagrange function at D; the value of the
  109. # (NUM_VARS+1)th Lagrange function is 1 - sum(SIMID). [SIMID, 1 - sum(SIMID)] is the counterpart of
  110. # VLAG in UOBYQA and DEN in NEWUOA/BOBYQA/LINCOA.
  111. simid = matprod(simi, d)
  112. score = weight * abs(np.array([*simid, 1 - primasum(simid)]))
  113. # If XIMPROVED = False (D does not render a better X), set SCORE[NUM_VARS] = -1 to avoid JDROP = NUM_VARS.
  114. if not ximproved:
  115. score[num_vars] = -1
  116. # score[j] is NaN implies SIMID[j] is NaN, but we want abs(SIMID) to be big. So we
  117. # exclude such j.
  118. score[np.isnan(score)] = -1
  119. jdrop = None
  120. # The following if statement works a bit better than
  121. # `if any(score > 1) or (any(score > 0) and ximproved)` from Powell's UOBYQA and
  122. # NEWUOA code.
  123. if any(score > 0): # Powell's BOBYQA and LINCOA code.
  124. jdrop = np.argmax(score)
  125. if (ximproved and jdrop is None):
  126. jdrop = np.argmax(distsq)
  127. #==================#
  128. # Calculation ends #
  129. #==================#
  130. # Postconditions
  131. if DEBUGGING:
  132. assert jdrop is None or (0 <= jdrop < num_vars + 1)
  133. assert jdrop <= num_vars or ximproved
  134. assert jdrop >= 0 or not ximproved
  135. # JDROP >= 1 when XIMPROVED = TRUE unless NaN occurs in DISTSQ, which should not happen if the
  136. # starting point does not contain NaN and the trust-region/geometry steps never contain NaN.
  137. return jdrop
  138. def geostep(jdrop, amat, bvec, conmat, cpen, cval, delbar, fval, simi):
  139. '''
  140. This function calculates a geometry step so that the geometry of the interpolation set is improved
  141. when SIM[: JDROP_GEO] is replaced with SIM[:, NUM_VARS] + D. See (15)--(17) of the COBYLA paper.
  142. '''
  143. # Sizes
  144. m_lcon = np.size(bvec, 0) if bvec is not None else 0
  145. num_constraints = np.size(conmat, 0)
  146. num_vars = np.size(simi, 0)
  147. # Preconditions
  148. if DEBUGGING:
  149. assert num_constraints >= m_lcon >= 0
  150. assert num_vars >= 1
  151. assert delbar > 0
  152. assert cpen > 0
  153. assert np.size(simi, 0) == num_vars and np.size(simi, 1) == num_vars
  154. assert np.isfinite(simi).all()
  155. assert np.size(fval) == num_vars + 1 and not any(np.isnan(fval) | np.isposinf(fval))
  156. assert np.size(conmat, 0) == num_constraints and np.size(conmat, 1) == num_vars + 1
  157. assert not np.any(np.isnan(conmat) | np.isposinf(conmat))
  158. assert np.size(cval) == num_vars + 1 and not any(cval < 0 | np.isnan(cval) | np.isposinf(cval))
  159. assert 0 <= jdrop < num_vars
  160. #====================#
  161. # Calculation starts #
  162. #====================#
  163. # SIMI[JDROP, :] is a vector perpendicular to the face of the simplex to the opposite of vertex
  164. # JDROP. Set D to the vector in this direction and with length DELBAR.
  165. d = simi[jdrop, :]
  166. d = delbar * (d / norm(d))
  167. # The code below chooses the direction of D according to an approximation of the merit function.
  168. # See (17) of the COBYLA paper and line 225 of Powell's cobylb.f.
  169. # Calculate the coefficients of the linear approximations to the objective and constraint functions.
  170. # N.B.: CONMAT and SIMI have been updated after the last trust-region step, but G and A have not.
  171. # So we cannot pass G and A from outside.
  172. g = matprod(fval[:num_vars] - fval[num_vars], simi)
  173. A = np.zeros((num_vars, num_constraints))
  174. A[:, :m_lcon] = amat.T if amat is not None else amat
  175. A[:, m_lcon:] = matprod((conmat[m_lcon:, :num_vars] -
  176. np.tile(conmat[m_lcon:, num_vars], (num_vars, 1)).T), simi).T
  177. # CVPD and CVND are the predicted constraint violation of D and -D by the linear models.
  178. cvpd = np.max(np.append(0, conmat[:, num_vars] + matprod(d, A)))
  179. cvnd = np.max(np.append(0, conmat[:, num_vars] - matprod(d, A)))
  180. if -inprod(d, g) + cpen * cvnd < inprod(d, g) + cpen * cvpd:
  181. d *= -1
  182. #==================#
  183. # Calculation ends #
  184. #==================#
  185. # Postconditions
  186. if DEBUGGING:
  187. assert np.size(d) == num_vars and all(np.isfinite(d))
  188. # In theory, ||S|| == DELBAR, which may be false due to rounding, but not too far.
  189. # It is crucial to ensure that the geometry step is nonzero, which holds in theory.
  190. assert 0.9 * delbar < np.linalg.norm(d) <= 1.1 * delbar
  191. return d