#NEWLINE# def solve_trust_region_2d( B , g , Delta ) : #NEWLINE# #INDENT# 'Solve a general trust-region problem in 2 dimensions.\n    \n    The problem is reformulated as a 4-th order algebraic equation,\n    the solution of which is found by numpy.roots.\n    \n    Parameters\n    ----------\n    B : ndarray, shape (2, 2)\n        Symmetric matrix, defines a quadratic term of the function.\n    g : ndarray, shape (2,)\n        Defines a linear term of the function.\n    Delta : float\n        Radius of a trust region.\n    \n    Returns\n    -------\n    p : ndarray, shape (2,)\n        Found solution.\n    newton_step : bool\n        Whether the returned solution is the Newton step which lies within\n        the trust region.\n    ' #NEWLINE# try : #NEWLINE# #INDENT# ( R , lower ) = cho_factor ( B ) #NEWLINE# p = ( - cho_solve ( ( R , lower ) , g ) ) #NEWLINE# if ( np . dot ( p , p ) <= ( Delta ** 2 ) ) : #NEWLINE# #INDENT# return ( p , True ) #NEWLINE# #UNINDENT# #UNINDENT# except LinAlgError : #NEWLINE# #INDENT# pass #NEWLINE# #UNINDENT# a = ( B [ ( 0 , 0 ) ] * ( Delta ** 2 ) ) #NEWLINE# b = ( B [ ( 0 , 1 ) ] * ( Delta ** 2 ) ) #NEWLINE# c = ( B [ ( 1 , 1 ) ] * ( Delta ** 2 ) ) #NEWLINE# d = ( g [ 0 ] * Delta ) #NEWLINE# f = ( g [ 1 ] * Delta ) #NEWLINE# coeffs = np . array ( [ ( ( - b ) + d ) , ( 2 * ( ( a - c ) + f ) ) , ( 6 * b ) , ( 2 * ( ( ( - a ) + c ) + f ) ) , ( ( - b ) - d ) ] ) #NEWLINE# t = np . roots ( coeffs ) #NEWLINE# t = np . real ( t [ np . isreal ( t ) ] ) #NEWLINE# p = ( Delta * np . vstack ( ( ( ( 2 * t ) / ( 1 + ( t ** 2 ) ) ) , ( ( 1 - ( t ** 2 ) ) / ( 1 + ( t ** 2 ) ) ) ) ) ) #NEWLINE# value = ( ( 0.5 * np . sum ( ( p * B . dot ( p ) ) , axis = 0 ) ) + np . dot ( g , p ) ) #NEWLINE# i = np . argmin ( value ) #NEWLINE# p = p [ : , i ] #NEWLINE# return ( p , False )