idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
40,000
public static PolynomialRoots createRootFinder ( int maxCoefficients , RootFinderType which ) { switch ( which ) { case STURM : FindRealRootsSturm sturm = new FindRealRootsSturm ( maxCoefficients , - 1 , 1e-10 , 200 , 200 ) ; return new WrapRealRootsSturm ( sturm ) ; case EVD : return new RootFinderCompanion ( ) ; default : throw new IllegalArgumentException ( "Unknown algorithm: " + which ) ; } }
Creates different polynomial root finders .
40,001
public static boolean gradient ( FunctionNtoS func , FunctionNtoN gradient , double param [ ] , double tol ) { return gradient ( func , gradient , param , tol , Math . sqrt ( UtilEjml . EPS ) ) ; }
Compares the passed in gradient function to a numerical calculation . Comparison is done using an absolute value .
40,002
protected boolean bracket ( ) { function . setInput ( stp ) ; if ( mode != 0 ) { fp = function . computeFunction ( ) ; gp = Double . NaN ; } else { mode = 1 ; } if ( fp > valueZero + ftol * stp * derivZero ) { setModeToSection ( stprev , fprev , stp ) ; return false ; } if ( fp >= fprev ) { setModeToSection ( stprev , fprev , stp ) ; return false ; } gp = function . computeDerivative ( ) ; if ( Math . abs ( gp ) <= - gtol * derivZero ) { return true ; } if ( gp >= 0 ) { setModeToSection ( stp , fp , stprev ) ; return false ; } if ( stmax <= 2 * stp - stprev ) { stprev = stp ; gprev = gp ; fprev = fp ; stp = stmax ; updated = true ; } else { double temp = stp ; stp = interpolate ( 2 * stp - stprev , Math . min ( stpmax , stp + t1 * ( stp - stprev ) ) ) ; stprev = temp ; gprev = gp ; fprev = fp ; updated = true ; } if ( checkSmallStep ( ) ) { if ( verbose != null ) verbose . println ( "WARNING: Small steps" ) ; return true ; } return false ; }
Searches for an upper bound .
40,003
protected boolean section ( ) { double temp = stp ; stp = interpolate ( pLow + t2 * ( pHi - pLow ) , pHi - t3 * ( pHi - pLow ) ) ; updated = true ; if ( ! Double . isNaN ( gp ) ) { stprev = temp ; fprev = fp ; gprev = gp ; } if ( checkSmallStep ( ) ) { if ( verbose != null ) verbose . println ( "WARNING: Small steps" ) ; return true ; } function . setInput ( stp ) ; fp = function . computeFunction ( ) ; gp = Double . NaN ; if ( fp > valueZero + ftol * stp * derivZero || fp >= fLow ) { pHi = stp ; } else { gp = function . computeDerivative ( ) ; if ( Math . abs ( gp ) <= - gtol * derivZero ) return true ; if ( gp * ( pHi - pLow ) >= 0 ) pHi = pLow ; if ( Math . abs ( ( pLow - stp ) * gp ) <= tolStep ) { return true ; } pLow = stp ; fLow = fp ; } return false ; }
Using the found bracket for alpha it searches for a better estimate .
40,004
protected boolean checkSmallStep ( ) { double max = Math . max ( stp , stprev ) ; return ( Math . abs ( stp - stprev ) / max < tolStep ) ; }
Checks to see if alpha is changing by a significant amount . If it change is too small it can get stuck in a loop \
40,005
protected double interpolate ( double boundA , double boundB ) { double alphaNew ; if ( Double . isNaN ( gp ) ) { alphaNew = SearchInterpolate . quadratic ( fprev , gprev , stprev , fp , stp ) ; } else { alphaNew = SearchInterpolate . cubic2 ( fprev , gprev , stprev , fp , gp , stp ) ; if ( Double . isNaN ( alphaNew ) ) alphaNew = SearchInterpolate . quadratic ( fprev , gprev , stprev , fp , stp ) ; } double l , u ; if ( boundA < boundB ) { l = boundA ; u = boundB ; } else { l = boundB ; u = boundA ; } if ( alphaNew < l ) alphaNew = l ; else if ( alphaNew > u ) alphaNew = u ; return alphaNew ; }
Use either quadratic of cubic interpolation to guess the minimum .
40,006
private List < Results > process ( FunctionStoS f , FunctionStoS g , double ... initSteps ) { List < Results > results = new ArrayList < Results > ( ) ; for ( double step : initSteps ) { results . add ( performTest ( f , g , step , 0 , Double . POSITIVE_INFINITY ) ) ; } return results ; }
Processes and compile results for the function at the specified initial steps
40,007
public void sort ( int data [ ] , int begin , int end ) { histogram . fill ( 0 ) ; for ( int i = begin ; i < end ; i ++ ) { histogram . data [ data [ i ] - minValue ] ++ ; } int index = begin ; for ( int i = 0 ; i < histogram . size ; i ++ ) { int N = histogram . get ( i ) ; int value = i + minValue ; for ( int j = 0 ; j < N ; j ++ ) { data [ index ++ ] = value ; } } }
Sorts the data in the array .
40,008
public void sort ( int input [ ] , int startIndex , int output [ ] , int startOutput , int length ) { histogram . fill ( 0 ) ; for ( int i = 0 ; i < length ; i ++ ) { histogram . data [ input [ i + startIndex ] - minValue ] ++ ; } int index = startOutput ; for ( int i = 0 ; i < histogram . size ; i ++ ) { int N = histogram . get ( i ) ; int value = i + minValue ; for ( int j = 0 ; j < N ; j ++ ) { output [ index ++ ] = value ; } } }
Sort routine which does not modify the input array . Input and output arrays can be the same instance .
40,009
public void computeDistance ( List < Point2D > obs , double [ ] distance ) { for ( int i = 0 ; i < obs . size ( ) ; i ++ ) { distance [ i ] = computeDistance ( obs . get ( i ) ) ; } }
There are some situations where processing everything as a list can speed things up a lot . This is not one of them .
40,010
public static void sort ( double [ ] data ) { int i = 0 , j ; final int n = data . length ; double a ; try { for ( j = 1 ; ; j ++ ) { a = data [ j ] ; try { for ( i = j ; data [ i - 1 ] > a ; i -- ) { data [ i ] = data [ i - 1 ] ; } } catch ( ArrayIndexOutOfBoundsException e ) { } data [ i ] = a ; } } catch ( ArrayIndexOutOfBoundsException e ) { } }
Sorts data into ascending order
40,011
protected KdTree . Node computeBranch ( List < P > points , GrowQueue_I32 indexes ) { List < P > left = new ArrayList < > ( points . size ( ) / 2 ) ; List < P > right = new ArrayList < > ( points . size ( ) / 2 ) ; GrowQueue_I32 leftIndexes , rightIndexes ; if ( indexes == null ) { leftIndexes = null ; rightIndexes = null ; } else { leftIndexes = new GrowQueue_I32 ( points . size ( ) / 2 ) ; rightIndexes = new GrowQueue_I32 ( points . size ( ) / 2 ) ; } splitter . splitData ( points , indexes , left , leftIndexes , right , rightIndexes ) ; KdTree . Node node = memory . requestNode ( ) ; node . split = splitter . getSplitAxis ( ) ; node . point = splitter . getSplitPoint ( ) ; node . index = splitter . getSplitIndex ( ) ; node . left = computeChild ( left , leftIndexes ) ; left = null ; leftIndexes = null ; node . right = computeChild ( right , rightIndexes ) ; return node ; }
Given the data inside this particular node select a point for the node and compute the node s children
40,012
protected KdTree . Node computeChild ( List < P > points , GrowQueue_I32 indexes ) { if ( points . size ( ) == 0 ) return null ; if ( points . size ( ) == 1 ) { return createLeaf ( points , indexes ) ; } else { return computeBranch ( points , indexes ) ; } }
Creates a child by checking to see if it is a leaf or branch .
40,013
private KdTree . Node createLeaf ( List < P > points , GrowQueue_I32 indexes ) { int index = indexes == null ? - 1 : indexes . get ( 0 ) ; return memory . requestNode ( points . get ( 0 ) , index ) ; }
Convenient function for creating a leaf node
40,014
public void remove ( int first , int last ) { if ( last < first ) throw new IllegalArgumentException ( "first <= last" ) ; if ( last >= size ) throw new IllegalArgumentException ( "last must be less than the max size" ) ; int delta = last - first + 1 ; for ( int i = last + 1 ; i < size ; i ++ ) { data [ i - delta ] = data [ i ] ; } size -= delta ; }
Removes elements from the list starting at first and ending at last
40,015
public void printHex ( ) { System . out . print ( "[ " ) ; for ( int i = 0 ; i < size ; i ++ ) { System . out . printf ( "0x%02X " , data [ i ] ) ; } System . out . print ( "]" ) ; }
Prints the queue to stdout as a hex array
40,016
public int indexOf ( byte value ) { for ( int i = 0 ; i < size ; i ++ ) { if ( data [ i ] == value ) return i ; } return - 1 ; }
Returns the index of the first element with the specified value . return - 1 if it wasn t found
40,017
public void computeRange ( SortableParameter_F32 input [ ] , int start , int length ) { if ( length == 0 ) { divisor = 0 ; return ; } float min , max ; min = max = input [ start ] . sortValue ; for ( int i = 1 ; i < length ; i ++ ) { float val = input [ start + i ] . sortValue ; if ( val < min ) min = val ; else if ( val > max ) max = val ; } setRange ( min , max ) ; }
Examines the list and computes the range from it
40,018
public void sortIndex ( float input [ ] , int start , int length , int indexes [ ] ) { for ( int i = 0 ; i < length ; i ++ ) indexes [ i ] = i ; for ( int i = 0 ; i < histIndexes . size ; i ++ ) { histIndexes . get ( i ) . reset ( ) ; } for ( int i = 0 ; i < length ; i ++ ) { int indexInput = i + start ; int discretized = ( int ) ( ( input [ indexInput ] - minValue ) / divisor ) ; histIndexes . data [ discretized ] . add ( indexInput ) ; } int index = 0 ; for ( int i = 0 ; i < histIndexes . size ; i ++ ) { GrowQueue_I32 matches = histIndexes . get ( i ) ; for ( int j = 0 ; j < matches . size ; j ++ ) { indexes [ index ++ ] = matches . data [ j ] ; } } }
Sort routine which does not modify the input array and instead maintains a list of indexes .
40,019
public void sortObject ( SortableParameter_F32 input [ ] , int start , int length ) { for ( int i = 0 ; i < histIndexes . size ; i ++ ) { histObjs [ i ] . reset ( ) ; } for ( int i = 0 ; i < length ; i ++ ) { int indexInput = i + start ; SortableParameter_F32 p = input [ indexInput ] ; int discretized = ( int ) ( ( p . sortValue - minValue ) / divisor ) ; histObjs [ discretized ] . add ( p ) ; } int index = start ; for ( int i = 0 ; i < histIndexes . size ; i ++ ) { FastQueue < SortableParameter_F32 > matches = histObjs [ i ] ; for ( int j = 0 ; j < matches . size ; j ++ ) { input [ index ++ ] = matches . data [ j ] ; } } }
Sorts the input list
40,020
protected void searchNode ( P target , KdTree . Node n ) { while ( n != null ) { checkBestDistance ( n , target ) ; if ( n . isLeaf ( ) ) break ; KdTree . Node nearer , further ; double splitValue = distance . valueAt ( ( P ) n . point , n . split ) ; if ( distance . valueAt ( target , n . split ) <= splitValue ) { nearer = n . left ; further = n . right ; } else { nearer = n . right ; further = n . left ; } double dx = splitValue - distance . valueAt ( target , n . split ) ; if ( further != null && canImprove ( dx * dx ) ) { addToQueue ( dx * dx , further , target ) ; } n = nearer ; } }
Traverse a node down to a leaf . Unexplored branches are added to the priority queue .
40,021
protected void addToQueue ( double closestDistanceSq , KdTree . Node node , P target ) { if ( ! node . isLeaf ( ) ) { Helper h ; if ( unused . isEmpty ( ) ) { h = new Helper ( ) ; } else { h = unused . remove ( unused . size ( ) - 1 ) ; } h . closestPossibleSq = closestDistanceSq ; h . node = node ; queue . add ( h ) ; } else { checkBestDistance ( node , target ) ; } }
Adds a node to the priority queue .
40,022
protected final double [ ] selectNextSeed ( List < double [ ] > points , double target ) { double sum = 0 ; for ( int i = 0 ; i < distance . size ( ) ; i ++ ) { sum += distance . get ( i ) ; double fraction = sum / totalDistance ; if ( fraction >= target ) return points . get ( i ) ; } throw new RuntimeException ( "This shouldn't happen" ) ; }
Randomly selects the next seed . The chance of a seed is based upon its distance from the closest cluster . Larger distances mean more likely .
40,023
protected final void updateDistances ( List < double [ ] > points , double [ ] clusterNew ) { totalDistance = 0 ; for ( int i = 0 ; i < distance . size ( ) ; i ++ ) { double dOld = distance . get ( i ) ; double dNew = StandardKMeans_F64 . distanceSq ( points . get ( i ) , clusterNew ) ; if ( dNew < dOld ) { distance . data [ i ] = dNew ; totalDistance += dNew ; } else { totalDistance += dOld ; } } }
Updates the list of distances from a point to the closest cluster . Update list of total distances
40,024
public void precomputeAll ( ) { precomputes . resize ( mixtures . size ( ) ) ; for ( int i = 0 ; i < precomputes . size ; i ++ ) { precomputes . get ( i ) . setGaussian ( mixtures . get ( i ) ) ; } }
Precomputes likelihood for all the mixtures
40,025
public static void fillCounting ( int [ ] array , int offset , int length ) { for ( int i = 0 ; i < length ; i ++ ) { array [ i + offset ] = i ; } }
Sets each element within range to a number counting up
40,026
public static void shuffle ( byte [ ] array , int offset , int length , Random rand ) { for ( int i = 0 ; i < length ; i ++ ) { int src = rand . nextInt ( length - i ) ; byte tmp = array [ offset + src + i ] ; array [ offset + src + i ] = array [ offset + i ] ; array [ offset + i ] = tmp ; } }
Randomly shuffle the array
40,027
public LineSearchMore94 setConvergence ( double ftol , double gtol , double xtol ) { if ( ftol < 0 ) throw new IllegalArgumentException ( "ftol must be >= 0 " ) ; if ( gtol < 0 ) throw new IllegalArgumentException ( "gtol must be >= 0 " ) ; if ( xtol < 0 ) throw new IllegalArgumentException ( "xtol must be >= 0 " ) ; this . ftol = ftol ; this . gtol = gtol ; this . xtol = xtol ; return this ; }
Configures the line search .
40,028
private void dcstep ( ) { double sgnd = gp * Math . signum ( gx ) ; double stpf ; if ( fp > fx ) { stpf = handleCase1 ( ) ; } else if ( sgnd < 0 ) { stpf = handleCase2 ( ) ; } else if ( Math . abs ( gp ) < Math . abs ( gx ) ) { stpf = handleCase3 ( ) ; } else { stpf = handleCase4 ( ) ; } if ( fp > fx ) { sty = stp ; fy = fp ; gy = gp ; } else { if ( sgnd < 0 ) { sty = stx ; fy = fx ; gy = gx ; } stx = stp ; fx = fp ; gx = gp ; } stp = stpf ; updated = true ; }
Computes the new step and updates fx fy gx dy .
40,029
private double handleCase1 ( ) { double stpc = SearchInterpolate . cubic2 ( fx , gx , stx , fp , gp , stp ) ; double stpq = SearchInterpolate . quadratic ( fx , gx , stx , fp , stp ) ; bracket = true ; if ( Math . abs ( stpc - stx ) < Math . abs ( stpq - stx ) ) { return stpc ; } else { return stpc + ( stpq - stpc ) / 2.0 ; } }
stp has a higher value than stx . The minimum must be between these two values . Pick a point which is close to stx since it has a lower value .
40,030
private double handleCase2 ( ) { double stpc = SearchInterpolate . cubic2 ( fp , gp , stp , fx , gx , stx ) ; double stpq = SearchInterpolate . quadratic2 ( gp , stp , gx , stx ) ; bracket = true ; if ( Math . abs ( stpc - stp ) > Math . abs ( stpq - stp ) ) { return stpc ; } else { return stpq ; } }
The sign of the derivative has swapped indicating that the function is on the other side of the dip and that a bracket has been found .
40,031
private double handleCase3 ( ) { double stpf ; double stpc = SearchInterpolate . cubicSafe ( fp , gp , stp , fx , gx , stx , stmin , stmax ) ; double stpq = SearchInterpolate . quadratic2 ( gp , stp , gx , stx ) ; if ( bracket ) { if ( Math . abs ( stpc - stp ) < Math . abs ( stpq - stp ) ) { stpf = stpc ; } else { stpf = stpq ; } if ( stp > stx ) { stpf = Math . min ( stp + p66 * ( sty - stp ) , stpf ) ; } else { stpf = Math . max ( stp + p66 * ( sty - stp ) , stpf ) ; } } else { if ( Math . abs ( stpc - stp ) > Math . abs ( stpq - stp ) ) { stpf = stpc ; } else { stpf = stpq ; } stpf = Math . min ( stmax , stpf ) ; stpf = Math . max ( stmin , stpf ) ; } return stpf ; }
The derivative at stp has a smaller magnitude than at stx and is likely to be closer to the minimum . However there are special cases that need to be dealt with here .
40,032
private double handleCase4 ( ) { if ( bracket ) { return SearchInterpolate . cubic2 ( fp , gp , stp , fy , gy , sty ) ; } else if ( stp > stx ) { return stmax ; } else { return stmin ; } }
Lower function value . On the same side of the dip because the gradients have the same sign . The magnitude of the derivative did not decrease .
40,033
private void computeAxisVariance ( List < P > points ) { int numPoints = points . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { mean [ i ] = 0 ; var [ i ] = 0 ; } for ( int i = 0 ; i < numPoints ; i ++ ) { P p = points . get ( i ) ; for ( int j = 0 ; j < N ; j ++ ) { mean [ j ] += distance . valueAt ( p , j ) ; } } for ( int i = 0 ; i < N ; i ++ ) { mean [ i ] /= numPoints ; } for ( int i = 0 ; i < numPoints ; i ++ ) { P p = points . get ( i ) ; for ( int j = 0 ; j < N ; j ++ ) { double d = mean [ j ] - distance . valueAt ( p , j ) ; var [ j ] += d * d ; } } }
Select the maximum variance as the split
40,034
private void quickSelect ( List < P > points , int splitAxis , int medianNum ) { int numPoints = points . size ( ) ; if ( tmp . length < numPoints ) { tmp = new double [ numPoints ] ; indexes = new int [ numPoints ] ; } for ( int i = 0 ; i < numPoints ; i ++ ) { tmp [ i ] = distance . valueAt ( points . get ( i ) , splitAxis ) ; } QuickSelect . selectIndex ( tmp , medianNum , numPoints , indexes ) ; }
Uses quick - select to find the median value
40,035
public void init ( List < T > list , int bucketSize ) { if ( list . size ( ) < bucketSize ) { throw new RuntimeException ( "There needs to be more than or equal to elements in the 'list' that there are in the bucket" ) ; } this . k = bucketSize ; this . c = bucketSize - 1 ; N = list . size ( ) ; bins = new int [ bucketSize ] ; for ( int i = 0 ; i < bins . length ; i ++ ) { bins [ i ] = i ; } this . a = list ; state = 1 ; }
Initialize with a new list and bucket size
40,036
public boolean next ( ) { if ( state == 2 ) return false ; else state = 1 ; bins [ c ] ++ ; if ( bins [ c ] >= N ) { boolean allgood = false ; for ( int i = c - 1 ; i >= 0 ; i -- ) { bins [ i ] ++ ; if ( bins [ i ] <= ( N - ( k - i ) ) ) { allgood = true ; for ( int j = i + 1 ; j < k ; j ++ ) { bins [ j ] = bins [ j - 1 ] + 1 ; } break ; } } if ( ! allgood ) { state = 2 ; for ( int j = 0 ; j < bins . length ; j ++ ) { bins [ j ] = j + N - bins . length ; } } return allgood ; } return true ; }
This will shuffle the elements in and out of the bins . When all combinations have been exhausted an ExhaustedException will be thrown .
40,037
public List < T > getBucket ( List < T > storage ) { if ( storage == null ) storage = new ArrayList < T > ( ) ; else storage . clear ( ) ; for ( int i = 0 ; i < bins . length ; i ++ ) { storage . add ( a . get ( bins [ i ] ) ) ; } return storage ; }
Extracts the entire bucket . Will add elements to the provided list or create a new one
40,038
public List < T > getOutside ( List < T > storage ) { if ( storage == null ) { storage = new ArrayList < T > ( ) ; } else { storage . clear ( ) ; } storage . addAll ( a ) ; for ( int i = bins . length - 1 ; i >= 0 ; i -- ) { storage . remove ( bins [ i ] ) ; } return storage ; }
This returns all the items that are not currently inside the bucket
40,039
public void prune ( ) { Iterator < PointIndex < Point > > iter = allPoints . iterator ( ) ; int index = 0 ; while ( iter . hasNext ( ) ) { iter . next ( ) ; if ( origErrors [ index ++ ] >= pruneVal ) { iter . remove ( ) ; } } }
Removes all samples which have an error larger than the specified percentile error .
40,040
public static PolynomialRoots createRootFinder ( RootFinderType type , int maxDegree ) { switch ( type ) { case EVD : return new RootFinderCompanion ( ) ; case STURM : FindRealRootsSturm sturm = new FindRealRootsSturm ( maxDegree , - 1 , 1e-10 , 30 , 20 ) ; return new WrapRealRootsSturm ( sturm ) ; } throw new IllegalArgumentException ( "Unknown type" ) ; }
Creates a generic polynomial root finding class which will return all real or all real and complex roots depending on the algorithm selected .
40,041
public T grow ( ) { if ( size >= data . length ) { T a = createInstance ( ) ; add ( a ) ; return a ; } else { T a = data [ ( start + size ) % data . length ] ; if ( a == null ) { data [ ( start + size ) % data . length ] = a = createInstance ( ) ; } size ++ ; return a ; } }
Adds a new element to the end of the list and returns it . If the inner array isn t large enough then it will grow .
40,042
public T growW ( ) { T a ; if ( size >= data . length ) { a = data [ start ] ; if ( a == null ) data [ start ] = a = createInstance ( ) ; start = ( start + 1 ) % data . length ; } else { a = data [ ( start + size ) % data . length ] ; if ( a == null ) data [ ( start + size ) % data . length ] = a = createInstance ( ) ; size ++ ; } return a ; }
Adds a new element to the end of the list and returns it . If the inner array isn t large enough then the oldest element will be written over .
40,043
public void initialize ( double [ ] initial , int numberOfParameters , double minimumFunctionValue ) { super . initialize ( initial , numberOfParameters , minimumFunctionValue ) ; y . reshape ( numberOfParameters , 1 ) ; xPrevious . reshape ( numberOfParameters , 1 ) ; x . reshape ( numberOfParameters , 1 ) ; gradientPrevious . reshape ( numberOfParameters , 1 ) ; gradientPrevious . zero ( ) ; firstIteration = true ; }
Override parent to initialize matrices
40,044
protected boolean wolfeCondition ( DMatrixRMaj s , DMatrixRMaj y , DMatrixRMaj g_k ) { double left = CommonOps_DDRM . dot ( y , s ) ; double g_s = CommonOps_DDRM . dot ( g_k , s ) ; double right = ( c2 - 1 ) * g_s ; if ( left >= right ) { return ( fx - f_prev ) <= c1 * g_s ; } return false ; }
Indicates if there s sufficient decrease and curvature . If the Wolfe condition is meet then the Hessian will be positive definite .
40,045
public void reset ( ) { Element e = first ; while ( e != null ) { Element n = e . next ; e . clear ( ) ; available . add ( e ) ; e = n ; } first = last = null ; size = 0 ; }
Puts the linked list back into its initial state . Elements are saved for later use .
40,046
public Element < T > getElement ( int index , boolean fromFront ) { if ( index > size || index < 0 ) { throw new IllegalArgumentException ( "index is out of bounds" ) ; } if ( fromFront ) { Element < T > e = first ; for ( int i = 0 ; i < index ; i ++ ) { e = e . next ; } return e ; } else { Element < T > e = last ; for ( int i = 0 ; i < index ; i ++ ) { e = e . previous ; } return e ; } }
Returns the N th element when counting from the from or from the back
40,047
public Element < T > pushHead ( T object ) { Element < T > e = requestNew ( ) ; e . object = object ; if ( first == null ) { first = last = e ; } else { e . next = first ; first . previous = e ; first = e ; } size ++ ; return e ; }
Adds the element to the front of the list .
40,048
public Element < T > pushTail ( T object ) { Element < T > e = requestNew ( ) ; e . object = object ; if ( last == null ) { first = last = e ; } else { e . previous = last ; last . next = e ; last = e ; } size ++ ; return e ; }
Adds the element to the back of the list .
40,049
public Element < T > insertAfter ( Element < T > previous , T object ) { Element < T > e = requestNew ( ) ; e . object = object ; e . previous = previous ; e . next = previous . next ; if ( e . next != null ) { e . next . previous = e ; } else { last = e ; } previous . next = e ; size ++ ; return e ; }
Inserts the object into a new element after the provided element .
40,050
public Element < T > insertBefore ( Element < T > next , T object ) { Element < T > e = requestNew ( ) ; e . object = object ; e . previous = next . previous ; e . next = next ; if ( e . previous != null ) { e . previous . next = e ; } else { first = e ; } next . previous = e ; size ++ ; return e ; }
Inserts the object into a new element before the provided element .
40,051
public void swap ( Element < T > a , Element < T > b ) { if ( a . next == b ) { if ( a . previous != null ) { a . previous . next = b ; } if ( b . next != null ) { b . next . previous = a ; } Element < T > tmp = a . previous ; a . previous = b ; a . next = b . next ; b . previous = tmp ; b . next = a ; if ( first == a ) first = b ; if ( last == b ) last = a ; } else if ( a . previous == b ) { if ( a . next != null ) { a . next . previous = b ; } if ( b . previous != null ) { b . previous . next = a ; } Element < T > tmp = a . next ; a . next = b ; a . previous = b . previous ; b . previous = a ; b . next = tmp ; if ( first == b ) first = a ; if ( last == a ) last = b ; } else { if ( a . next != null ) { a . next . previous = b ; } if ( a . previous != null ) { a . previous . next = b ; } if ( b . next != null ) { b . next . previous = a ; } if ( b . previous != null ) { b . previous . next = a ; } Element < T > tempNext = b . next ; Element < T > tempPrev = b . previous ; b . next = a . next ; b . previous = a . previous ; a . next = tempNext ; a . previous = tempPrev ; if ( a . next == null ) last = a ; else if ( b . next == null ) last = b ; if ( a . previous == null ) first = a ; else if ( b . previous == null ) first = b ; } }
Swaps the location of the two elements
40,052
public void remove ( Element < T > element ) { if ( element . next == null ) { last = element . previous ; } else { element . next . previous = element . previous ; } if ( element . previous == null ) { first = element . next ; } else { element . previous . next = element . next ; } size -- ; element . clear ( ) ; available . push ( element ) ; }
Removes the element from the list and saves the element data structure for later reuse .
40,053
public T removeHead ( ) { if ( first == null ) throw new IllegalArgumentException ( "Empty list" ) ; T ret = first . getObject ( ) ; Element < T > e = first ; available . push ( first ) ; if ( first . next != null ) { first . next . previous = null ; first = first . next ; } else { first = last = null ; } e . clear ( ) ; size -- ; return ret ; }
Removes the first element from the list
40,054
public Object removeTail ( ) { if ( last == null ) throw new IllegalArgumentException ( "Empty list" ) ; Object ret = last . getObject ( ) ; Element < T > e = last ; available . add ( last ) ; if ( last . previous != null ) { last . previous . next = null ; last = last . previous ; } else { first = last = null ; } e . clear ( ) ; size -- ; return ret ; }
Removes the last element from the list
40,055
public Element < T > find ( T object ) { Element < T > e = first ; while ( e != null ) { if ( e . object == object ) { return e ; } e = e . next ; } return null ; }
Returns the first element which contains object starting from the head .
40,056
public void addAll ( List < T > list ) { if ( list . isEmpty ( ) ) return ; Element < T > a = requestNew ( ) ; a . object = list . get ( 0 ) ; if ( first == null ) { first = a ; } else if ( last != null ) { last . next = a ; a . previous = last ; } for ( int i = 1 ; i < list . size ( ) ; i ++ ) { Element < T > b = requestNew ( ) ; b . object = list . get ( i ) ; a . next = b ; b . previous = a ; a = b ; } last = a ; size += list . size ( ) ; }
Add all elements in list into this linked list
40,057
public void addAll ( T [ ] array , int first , int length ) { if ( length <= 0 ) return ; Element < T > a = requestNew ( ) ; a . object = array [ first ] ; if ( this . first == null ) { this . first = a ; } else if ( last != null ) { last . next = a ; a . previous = last ; } for ( int i = 1 ; i < length ; i ++ ) { Element < T > b = requestNew ( ) ; b . object = array [ first + i ] ; a . next = b ; b . previous = a ; a = b ; } last = a ; size += length ; }
Adds the specified elements from array into this list
40,058
public void addMean ( double [ ] point , double responsibility ) { for ( int i = 0 ; i < mean . numRows ; i ++ ) { mean . data [ i ] += responsibility * point [ i ] ; } weight += responsibility ; }
Helper function for computing Gaussian parameters . Adds the point to mean and weight .
40,059
public void addCovariance ( double [ ] difference , double responsibility ) { int N = mean . numRows ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i ; j < N ; j ++ ) { covariance . data [ i * N + j ] += responsibility * difference [ i ] * difference [ j ] ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { covariance . data [ i * N + j ] = covariance . data [ j * N + i ] ; } } }
Helper function for computing Gaussian parameters . Adds the difference between point and mean to covariance adjusted by the weight .
40,060
public static GrowQueue_B zeros ( int length ) { GrowQueue_B out = new GrowQueue_B ( length ) ; out . size = length ; return out ; }
Creates a queue with the specified length as its size filled with false
40,061
public static int findMaxIndex ( int [ ] a ) { int max = a [ 0 ] ; int index = 0 ; for ( int i = 1 ; i < a . length ; i ++ ) { int val = a [ i ] ; if ( val > max ) { max = val ; index = i ; } } return index ; }
Finds the index in a with the largest value .
40,062
public void reset ( ) { unusedEdges . addAll ( usedEdges ) ; unusedNodes . addAll ( usedNodes ) ; usedEdges . clear ( ) ; usedNodes . clear ( ) ; }
Takes all the used nodes and makes them unused .
40,063
public void resetHard ( ) { for ( int i = 0 ; i < usedEdges . size ( ) ; i ++ ) { Edge < N , E > e = usedEdges . get ( i ) ; e . data = null ; e . dest = null ; } for ( int i = 0 ; i < usedNodes . size ( ) ; i ++ ) { Node < N , E > n = usedNodes . get ( i ) ; n . data = null ; n . edges . reset ( ) ; } unusedEdges . addAll ( usedEdges ) ; unusedNodes . addAll ( usedNodes ) ; usedEdges . clear ( ) ; usedNodes . clear ( ) ; }
Takes all the used nodes and makes them unused . Also dereferences any objects saved in data .
40,064
protected void init ( int initialMaxSize , Class < T > type , Factory < T > factory ) { this . size = 0 ; this . type = type ; this . factory = factory ; data = ( T [ ] ) Array . newInstance ( type , initialMaxSize ) ; if ( factory != null ) { for ( int i = 0 ; i < initialMaxSize ; i ++ ) { try { data [ i ] = createInstance ( ) ; } catch ( RuntimeException e ) { throw new RuntimeException ( "declareInstances is true, but createInstance() can't create a new instance. Maybe override createInstance()?" ) ; } } } }
Data structure initialization is done here so that child classes can declay initialization until they are ready
40,065
public void reverse ( ) { for ( int i = 0 ; i < size / 2 ; i ++ ) { T tmp = data [ i ] ; data [ i ] = data [ size - i - 1 ] ; data [ size - i - 1 ] = tmp ; } }
Reverse the item order in this queue .
40,066
public T get ( int index ) { if ( index >= size ) throw new IllegalArgumentException ( "Index out of bounds: index " + index + " size " + size ) ; return data [ index ] ; }
Returns the element at the specified index . Bounds checking is performed .
40,067
public T grow ( ) { if ( size < data . length ) { return data [ size ++ ] ; } else { growArray ( ( data . length + 1 ) * 2 ) ; return data [ size ++ ] ; } }
Returns a new element of data . If there are new data elements available then array will automatically grow .
40,068
public void remove ( int index ) { T removed = data [ index ] ; for ( int i = index + 1 ; i < size ; i ++ ) { data [ i - 1 ] = data [ i ] ; } data [ size - 1 ] = removed ; size -- ; }
Removes an element from the queue by shifting elements in the array down one and placing the removed element at the old end of the list .
40,069
public void growArray ( int length ) { if ( this . data . length >= length ) return ; T [ ] data = ( T [ ] ) Array . newInstance ( type , length ) ; System . arraycopy ( this . data , 0 , data , 0 , this . data . length ) ; if ( factory != null ) { for ( int i = this . data . length ; i < length ; i ++ ) { data [ i ] = createInstance ( ) ; } } this . data = data ; }
Increases the size of the internal array without changing the shape s size . If the array is already larger than the specified length then nothing is done . Elements previously stored in the array are copied over is a new internal array is declared .
40,070
protected void cauchyStep ( double regionRadius , DMatrixRMaj step ) { CommonOps_DDRM . scale ( - regionRadius , direction , step ) ; stepLength = regionRadius ; predictedReduction = regionRadius * ( owner . gradientNorm - 0.5 * regionRadius * gBg ) ; }
Computes the Cauchy step This is only called if the Cauchy point lies after or on the trust region
40,071
static double fractionCauchyToGN ( double lengthCauchy , double lengthGN , double lengthPtoGN , double region ) { double a = lengthGN , b = lengthCauchy , c = lengthPtoGN ; double cosineA = ( a * a - b * b - c * c ) / ( - 2.0 * b * c ) ; double angleA = Math . acos ( cosineA ) ; a = region ; double angleB = Math . asin ( ( b / a ) * Math . sin ( angleA ) ) ; double angleC = Math . PI - angleA - angleB ; c = Math . sqrt ( a * a + b * b - 2.0 * a * b * Math . cos ( angleC ) ) ; return c / lengthPtoGN ; }
Compute the fractional distance from P to GN where the point intersects the region s boundary
40,072
public DMatrixRMaj next ( DMatrixRMaj x ) { for ( int i = 0 ; i < r . numRows ; i ++ ) { r . set ( i , 0 , rand . nextGaussian ( ) ) ; } x . set ( mean ) ; multAdd ( A , r , x ) ; return x ; }
Makes a draw on the distribution and stores the results in parameter x
40,073
public void initialize ( List < Point > dataSet ) { bestFitPoints . clear ( ) ; if ( dataSet . size ( ) > matchToInput . length ) { matchToInput = new int [ dataSet . size ( ) ] ; bestMatchToInput = new int [ dataSet . size ( ) ] ; } }
Initialize internal data structures
40,074
public static < T > void randomDraw ( List < T > dataSet , int numSample , List < T > initialSample , Random rand ) { initialSample . clear ( ) ; for ( int i = 0 ; i < numSample ; i ++ ) { int indexLast = dataSet . size ( ) - i - 1 ; int indexSelected = rand . nextInt ( indexLast + 1 ) ; T a = dataSet . get ( indexSelected ) ; initialSample . add ( a ) ; dataSet . set ( indexSelected , dataSet . set ( indexLast , a ) ) ; } }
Performs a random draw in the dataSet . When an element is selected it is moved to the end of the list so that it can t be selected again .
40,075
@ SuppressWarnings ( { "ForLoopReplaceableByForEach" } ) protected void selectMatchSet ( List < Point > dataSet , double threshold , Model param ) { candidatePoints . clear ( ) ; modelDistance . setModel ( param ) ; for ( int i = 0 ; i < dataSet . size ( ) ; i ++ ) { Point point = dataSet . get ( i ) ; double distance = modelDistance . computeDistance ( point ) ; if ( distance < threshold ) { matchToInput [ candidatePoints . size ( ) ] = i ; candidatePoints . add ( point ) ; } } }
Looks for points in the data set which closely match the current best fit model in the optimizer .
40,076
protected void matchPointsToClusters ( List < double [ ] > points ) { sumDistance = 0 ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { double [ ] p = points . get ( i ) ; int bestCluster = findBestMatch ( p ) ; double [ ] c = workClusters . get ( bestCluster ) ; for ( int j = 0 ; j < c . length ; j ++ ) { c [ j ] += p [ j ] ; } memberCount . data [ bestCluster ] ++ ; labels . data [ i ] = bestCluster ; sumDistance += bestDistance ; } }
Finds the cluster which is the closest to each point . The point is the added to the sum for the cluster and its member count incremented
40,077
protected int findBestMatch ( double [ ] p ) { int bestCluster = - 1 ; bestDistance = Double . MAX_VALUE ; for ( int j = 0 ; j < clusters . size ; j ++ ) { double d = distanceSq ( p , clusters . get ( j ) ) ; if ( d < bestDistance ) { bestDistance = d ; bestCluster = j ; } } return bestCluster ; }
Searches for this cluster which is the closest to p
40,078
protected void updateClusterCenters ( ) { for ( int i = 0 ; i < clusters . size ; i ++ ) { double mc = memberCount . get ( i ) ; double [ ] w = workClusters . get ( i ) ; double [ ] c = clusters . get ( i ) ; for ( int j = 0 ; j < w . length ; j ++ ) { c [ j ] = w [ j ] / mc ; } } }
Sets the location of each cluster to the average location of all its members .
40,079
protected static double distanceSq ( double [ ] a , double [ ] b ) { double sum = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { double d = a [ i ] - b [ i ] ; sum += d * d ; } return sum ; }
Returns the euclidean distance squared between the two poits
40,080
public T requestInstance ( ) { T a ; if ( unused . size ( ) > 0 ) { a = unused . pop ( ) ; } else { a = createInstance ( ) ; } return a ; }
Either returns a recycled instance or a new one .
40,081
protected T createInstance ( ) { try { return targetClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } }
Creates a new instance using the class . overload this to handle more complex constructors
40,082
public void setFunction ( GradientLineFunction function , double funcMinValue ) { this . function = function ; this . funcMinValue = funcMinValue ; lineSearch . setFunction ( function , funcMinValue ) ; N = function . getN ( ) ; B = new DMatrixRMaj ( N , N ) ; searchVector = new DMatrixRMaj ( N , 1 ) ; g = new DMatrixRMaj ( N , 1 ) ; s = new DMatrixRMaj ( N , 1 ) ; y = new DMatrixRMaj ( N , 1 ) ; x = new DMatrixRMaj ( N , 1 ) ; temp0_Nx1 = new DMatrixRMaj ( N , 1 ) ; temp1_Nx1 = new DMatrixRMaj ( N , 1 ) ; }
Specify the function being optimized
40,083
private boolean computeSearchDirection ( ) { function . computeGradient ( temp0_Nx1 . data ) ; for ( int i = 0 ; i < N ; i ++ ) { y . data [ i ] = temp0_Nx1 . data [ i ] - g . data [ i ] ; g . data [ i ] = temp0_Nx1 . data [ i ] ; } if ( iterations != 0 ) { EquationsBFGS . inverseUpdate ( B , s , y , temp0_Nx1 , temp1_Nx1 ) ; } CommonOps_DDRM . mult ( - 1 , B , g , searchVector ) ; if ( ! setupLineSearch ( fx , x . data , g . data , searchVector . data ) ) { resetMatrixB ( ) ; CommonOps_DDRM . mult ( - 1 , B , g , searchVector ) ; setupLineSearch ( fx , x . data , g . data , searchVector . data ) ; } else if ( Math . abs ( derivAtZero ) <= gtol ) { if ( verbose != null ) { verbose . printf ( "finished select direction, gtest=%e\n" , Math . abs ( derivAtZero ) ) ; } System . arraycopy ( function . getCurrentState ( ) , 0 , x . data , 0 , N ) ; return terminateSearch ( true ) ; } mode = 1 ; iterations ++ ; return false ; }
Computes the next search direction using BFGS
40,084
private void resetMatrixB ( ) { double maxDiag = 0 ; for ( int i = 0 ; i < N ; i ++ ) { double d = Math . abs ( B . get ( i , i ) ) ; if ( d > maxDiag ) maxDiag = d ; } B . zero ( ) ; for ( int i = 0 ; i < N ; i ++ ) { B . set ( i , i , maxDiag ) ; } }
This is a total hack . Set B to a diagonal matrix where each diagonal element is the value of the largest absolute value in B . This will be SPD and hopefully not screw up the search .
40,085
private boolean performLineSearch ( ) { if ( lineSearch . iterate ( ) ) { if ( ! lineSearch . isConverged ( ) ) { if ( firstStep ) { initialStep /= 2 ; if ( initialStep != 0 ) { invokeLineInitialize ( fx , maxStep ) ; return false ; } else { if ( verbose != null && verboseLevel != 0 ) { verbose . println ( "Initial step reduced to zero" ) ; } return terminateSearch ( false ) ; } } else { return terminateSearch ( false ) ; } } else { firstStep = false ; } double step = lineSearch . getStep ( ) ; System . arraycopy ( function . getCurrentState ( ) , 0 , x . data , 0 , N ) ; for ( int i = 0 ; i < N ; i ++ ) s . data [ i ] = step * searchVector . data [ i ] ; updated = true ; double fstp = lineSearch . getFunction ( ) ; if ( verbose != null ) { double actualStep = NormOps_DDRM . fastNormF ( s ) ; double ftest_val = Math . abs ( fstp - fx ) / Math . abs ( fx ) ; double gtest_val = Math . abs ( derivAtZero ) ; verbose . printf ( "%-4d %9.3E %10.3E %9.3E %9.3E %9.3E %6.3f\n" , iterations , fstp , fstp - fx , actualStep , ftest_val , gtest_val , maxStep ) ; } if ( Math . abs ( fstp - fx ) <= ftol * Math . abs ( fx ) || Math . abs ( derivAtZero ) < gtol ) { if ( verbose != null ) { verbose . println ( "converged after line search." ) ; } return terminateSearch ( true ) ; } if ( fstp > fx ) { throw new RuntimeException ( "Bug! Worse results!" ) ; } fx = fstp ; mode = 0 ; } return false ; }
Performs a 1 - D line search along the chosen direction until the Wolfe conditions have been meet .
40,086
private void computeMean ( ) { meanError = 0 ; int size = allPoints . size ( ) ; for ( PointIndex < Point > inlier : allPoints ) { Point pt = inlier . data ; meanError += modelError . computeDistance ( pt ) ; } meanError /= size ; }
Computes the mean and standard deviation of the points from the model
40,087
public void initialize ( double initial [ ] , int numberOfParameters , double minimumFunctionValue ) { super . initialize ( initial , numberOfParameters ) ; tmp_p . reshape ( numberOfParameters , 1 ) ; regionRadius = config . regionInitial ; fx = cost ( x ) ; if ( verbose != null ) { verbose . println ( "Steps fx change |step| f-test g-test tr-ratio region " ) ; verbose . printf ( "%-4d %9.3E %10.3E %9.3E %9.3E %9.3E %6.2f %6.2E\n" , totalSelectSteps , fx , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , regionRadius ) ; } this . parameterUpdate . initialize ( this , numberOfParameters , minimumFunctionValue ) ; if ( fx <= minimumFunctionValue ) { if ( verbose != null ) { verbose . println ( "Converged minimum value" ) ; } mode = TrustRegionBase_F64 . Mode . CONVERGED ; } else { mode = TrustRegionBase_F64 . Mode . COMPUTE_DERIVATIVES ; } }
Specifies initial state of the search and completion criteria
40,088
protected boolean updateDerivates ( ) { functionGradientHessian ( x , sameStateAsCost , gradient , hessian ) ; if ( config . hessianScaling ) { computeHessianScaling ( ) ; applyHessianScaling ( ) ; } if ( checkConvergenceGTest ( gradient ) ) { if ( verbose != null ) { verbose . println ( "Converged g-test" ) ; } return true ; } gradientNorm = NormOps_DDRM . normF ( gradient ) ; if ( UtilEjml . isUncountable ( gradientNorm ) ) throw new OptimizationException ( "Uncountable. gradientNorm=" + gradientNorm ) ; parameterUpdate . initializeUpdate ( ) ; return false ; }
Computes all the derived data structures and attempts to update the parameters
40,089
protected boolean computeStep ( ) { if ( regionRadius == - 1 ) { parameterUpdate . computeUpdate ( p , Double . MAX_VALUE ) ; regionRadius = parameterUpdate . getStepLength ( ) ; if ( regionRadius == Double . MAX_VALUE || UtilEjml . isUncountable ( regionRadius ) ) { if ( verbose != null ) verbose . println ( "unconstrained initialization failed. Using Cauchy initialization instead." ) ; regionRadius = - 2 ; } else { if ( verbose != null ) verbose . println ( "unconstrained initialization radius=" + regionRadius ) ; } } if ( regionRadius == - 2 ) { regionRadius = solveCauchyStepLength ( ) * 10 ; parameterUpdate . computeUpdate ( p , regionRadius ) ; if ( verbose != null ) verbose . println ( "cauchy initialization radius=" + regionRadius ) ; } else { parameterUpdate . computeUpdate ( p , regionRadius ) ; } if ( config . hessianScaling ) undoHessianScalingOnParameters ( p ) ; CommonOps_DDRM . add ( x , p , x_next ) ; double fx_candidate = cost ( x_next ) ; if ( UtilEjml . isUncountable ( fx_candidate ) ) { throw new OptimizationException ( "Uncountable candidate cost. " + fx_candidate ) ; } sameStateAsCost = true ; return considerCandidate ( fx_candidate , fx , parameterUpdate . getPredictedReduction ( ) , parameterUpdate . getStepLength ( ) ) ; }
Changes the trust region s size and attempts to do a step again
40,090
protected boolean considerCandidate ( double fx_candidate , double fx_prev , double predictedReduction , double stepLength ) { double actualReduction = fx_prev - fx_candidate ; if ( actualReduction == 0 || predictedReduction == 0 ) { if ( verbose != null ) verbose . println ( totalFullSteps + " reduction of zero" ) ; return true ; } double ratio = actualReduction / predictedReduction ; if ( fx_candidate > fx_prev || ratio < 0.25 ) { regionRadius = 0.5 * regionRadius ; } else { if ( ratio > 0.75 ) { regionRadius = min ( max ( 3 * stepLength , regionRadius ) , config . regionMaximum ) ; } } if ( fx_candidate < fx_prev && ratio > 0 ) { boolean converged = checkConvergenceFTest ( fx_candidate , fx_prev ) ; if ( verbose != null ) { verbose . printf ( "%-4d %9.3E %10.3E %9.3E %9.3E %9.3E %6.2f %6.2E\n" , totalSelectSteps , fx_candidate , fx_candidate - fx_prev , stepLength , ftest_val , gtest_val , ratio , regionRadius ) ; if ( converged ) { System . out . println ( "Converged f-test" ) ; } } return acceptNewState ( converged , fx_candidate ) ; } else { mode = Mode . DETERMINE_STEP ; return false ; } }
Consider updating the system with the change in state p . The update will never be accepted if the cost function increases .
40,091
public void initialize ( double initial [ ] , int numberOfParameters , int numberOfFunctions ) { super . initialize ( initial , numberOfParameters ) ; lambda = config . dampeningInitial ; nu = NU_INITIAL ; residuals . reshape ( numberOfFunctions , 1 ) ; diagOrig . reshape ( numberOfParameters , 1 ) ; diagStep . reshape ( numberOfParameters , 1 ) ; computeResiduals ( x , residuals ) ; fx = costFromResiduals ( residuals ) ; mode = Mode . COMPUTE_DERIVATIVES ; if ( verbose != null ) { verbose . println ( "Steps fx change |step| f-test g-test tr-ratio lambda " ) ; verbose . printf ( "%-4d %9.3E %10.3E %9.3E %9.3E %9.3E %6.2f %6.2E\n" , totalSelectSteps , fx , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , lambda ) ; } }
Initializes the search .
40,092
protected boolean computeStep ( ) { if ( ! computeStep ( lambda , gradient , p ) ) { if ( config . mixture == 0.0 ) { throw new OptimizationException ( "Singular matrix encountered. Try setting mixture to a non-zero value" ) ; } lambda *= 4 ; if ( verbose != null ) verbose . println ( totalFullSteps + " Step computation failed. Increasing lambda" ) ; return maximumLambdaNu ( ) ; } if ( config . hessianScaling ) undoHessianScalingOnParameters ( p ) ; CommonOps_DDRM . add ( x , p , x_next ) ; computeResiduals ( x_next , residuals ) ; double fx_candidate = costFromResiduals ( residuals ) ; if ( UtilEjml . isUncountable ( fx_candidate ) ) throw new OptimizationException ( "Uncountable candidate score: " + fx_candidate ) ; double actualReduction = fx - fx_candidate ; double predictedReduction = computePredictedReduction ( p ) ; if ( actualReduction == 0 || predictedReduction == 0 ) { if ( verbose != null ) verbose . println ( totalFullSteps + " reduction of zero" ) ; return true ; } return processStepResults ( fx_candidate , actualReduction , predictedReduction ) ; }
Compute a new possible state and determine if it should be accepted or not . If accepted update the state
40,093
private boolean processStepResults ( double fx_candidate , double actualReduction , double predictedReduction ) { double ratio = actualReduction / predictedReduction ; boolean accepted ; if ( fx_candidate < fx ) { lambda = lambda * max ( 1.0 / 3.0 , 1.0 - Math . pow ( 2.0 * ratio - 1.0 , 3.0 ) ) ; nu = NU_INITIAL ; accepted = true ; } else { lambda *= nu ; nu *= 2 ; accepted = false ; } if ( UtilEjml . isUncountable ( lambda ) || UtilEjml . isUncountable ( nu ) ) throw new OptimizationException ( "BUG! lambda=" + lambda + " nu=" + nu ) ; if ( accepted ) { boolean converged = checkConvergenceFTest ( fx_candidate , fx ) ; if ( verbose != null ) { double length_p = NormOps_DDRM . normF ( p ) ; verbose . printf ( "%-4d %9.3E %10.3E %9.3E %9.3E %9.3E %6.3f %6.2E\n" , totalSelectSteps , fx_candidate , fx_candidate - fx , length_p , ftest_val , gtest_val , ratio , lambda ) ; if ( converged ) { verbose . println ( "Converged f-test" ) ; } } acceptNewState ( fx_candidate ) ; return maximumLambdaNu ( ) || converged ; } else return false ; }
Sees if this is an improvement worth accepting . Adjust dampening parameter and change the state if accepted .
40,094
private void acceptNewState ( double fx_candidate ) { DMatrixRMaj tmp = x ; x = x_next ; x_next = tmp ; fx = fx_candidate ; mode = Mode . COMPUTE_DERIVATIVES ; }
The new state has been accepted . Switch the internal state over to this
40,095
protected boolean computeStep ( double lambda , DMatrixRMaj gradient , DMatrixRMaj step ) { final double mixture = config . mixture ; for ( int i = 0 ; i < diagOrig . numRows ; i ++ ) { double v = min ( config . diagonal_max , max ( config . diagonal_min , diagOrig . data [ i ] ) ) ; diagStep . data [ i ] = v + lambda * ( mixture + ( 1.0 - mixture ) * v ) ; } hessian . setDiagonals ( diagStep ) ; if ( ! hessian . initializeSolver ( ) ) { return false ; } if ( hessian . solve ( gradient , step ) ) { CommonOps_DDRM . scale ( - 1 , step ) ; return true ; } else { return false ; } }
Adjusts the Hessian s diagonal elements value and computes the next step
40,096
public double evaluate ( double variable ) { if ( size == 0 ) { return 0 ; } else if ( size == 1 ) { return c [ 0 ] ; } else if ( Double . isInfinite ( variable ) ) { int degree = computeDegree ( ) ; if ( degree % 2 == 0 ) variable = Double . POSITIVE_INFINITY ; if ( c [ degree ] < 0 ) variable = variable == Double . POSITIVE_INFINITY ? Double . NEGATIVE_INFINITY : Double . POSITIVE_INFINITY ; return variable ; } double total = c [ size - 1 ] ; for ( int i = size - 2 ; i >= 0 ; i -- ) { total = c [ i ] + total * variable ; } return total ; }
Computes the polynomials output given the variable value Can handle infinite numbers
40,097
public boolean isIdentical ( Polynomial p , double tol ) { int m = Math . max ( p . size ( ) , size ( ) ) ; for ( int i = p . size ; i < m ; i ++ ) { if ( Math . abs ( c [ i ] ) > tol ) { return false ; } } for ( int i = size ; i < m ; i ++ ) { if ( Math . abs ( p . c [ i ] ) > tol ) { return false ; } } int n = Math . min ( p . size ( ) , size ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( Math . abs ( c [ i ] - p . c [ i ] ) > tol ) { return false ; } } return true ; }
Checks to see if the coefficients of two polynomials are identical to within tolerance . If the lengths of the polynomials are not the same then the extra coefficients in the longer polynomial must be within tolerance of zero .
40,098
public void truncateZeros ( double tol ) { int i = size - 1 ; for ( ; i >= 0 ; i -- ) { if ( Math . abs ( c [ i ] ) > tol ) break ; } size = i + 1 ; }
Prunes zero coefficients from the end of a sequence . A coefficient is zero if its absolute value is less than or equal to tolerance .
40,099
public void findNeighbor ( P target , int searchN , FastQueue < KdTreeResult > results ) { if ( searchN <= 0 ) throw new IllegalArgumentException ( "I'm sorry, but I refuse to search for less than or equal to 0 neighbors." ) ; if ( tree . root == null ) return ; this . searchN = searchN ; this . target = target ; this . mostDistantNeighborSq = maxDistanceSq ; stepClosest ( tree . root , results ) ; }
Finds the nodes which are closest to target and within range of the maximum distance .