idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
31,500
@ Indexable ( type = IndexableType . DELETE ) @ Override public CommerceWishListItem deleteCommerceWishListItem ( long commerceWishListItemId ) throws PortalException { return commerceWishListItemPersistence . remove ( commerceWishListItemId ) ; }
Deletes the commerce wish list item with the primary key from the database . Also notifies the appropriate model listeners .
62
23
31,501
@ Indexable ( type = IndexableType . DELETE ) @ Override public CommerceWishListItem deleteCommerceWishListItem ( CommerceWishListItem commerceWishListItem ) { return commerceWishListItemPersistence . remove ( commerceWishListItem ) ; }
Deletes the commerce wish list item from the database . Also notifies the appropriate model listeners .
61
19
31,502
public static com . liferay . commerce . product . model . CPInstance getCPInstance ( long CPInstanceId ) throws com . liferay . portal . kernel . exception . PortalException { return getService ( ) . getCPInstance ( CPInstanceId ) ; }
Returns the cp instance with the primary key .
57
9
31,503
@ Indexable ( type = IndexableType . DELETE ) @ Override public CommerceWarehouse deleteCommerceWarehouse ( long commerceWarehouseId ) throws PortalException { return commerceWarehousePersistence . remove ( commerceWarehouseId ) ; }
Deletes the commerce warehouse with the primary key from the database . Also notifies the appropriate model listeners .
52
21
31,504
protected void runSQL ( String sql ) { try { DataSource dataSource = commerceWarehousePersistence . getDataSource ( ) ; DB db = DBManagerUtil . getDB ( ) ; sql = db . buildSQL ( sql ) ; sql = PortalUtil . transformSQL ( sql ) ; SqlUpdate sqlUpdate = SqlUpdateFactoryUtil . getSqlUpdate ( dataSource , sql ) ; sqlUpdate . update ( ) ; } catch ( Exception e ) { throw new SystemException ( e ) ; } }
Performs a SQL query .
111
6
31,505
@ Override public void cacheResult ( CPDefinitionOptionValueRel cpDefinitionOptionValueRel ) { entityCache . putResult ( CPDefinitionOptionValueRelModelImpl . ENTITY_CACHE_ENABLED , CPDefinitionOptionValueRelImpl . class , cpDefinitionOptionValueRel . getPrimaryKey ( ) , cpDefinitionOptionValueRel ) ; finderCache . putResult ( FINDER_PATH_FETCH_BY_UUID_G , new Object [ ] { cpDefinitionOptionValueRel . getUuid ( ) , cpDefinitionOptionValueRel . getGroupId ( ) } , cpDefinitionOptionValueRel ) ; finderCache . putResult ( FINDER_PATH_FETCH_BY_C_K , new Object [ ] { cpDefinitionOptionValueRel . getCPDefinitionOptionRelId ( ) , cpDefinitionOptionValueRel . getKey ( ) } , cpDefinitionOptionValueRel ) ; cpDefinitionOptionValueRel . resetOriginalValues ( ) ; }
Caches the cp definition option value rel in the entity cache if it is enabled .
217
17
31,506
@ Override public void cacheResult ( List < CPDefinitionOptionValueRel > cpDefinitionOptionValueRels ) { for ( CPDefinitionOptionValueRel cpDefinitionOptionValueRel : cpDefinitionOptionValueRels ) { if ( entityCache . getResult ( CPDefinitionOptionValueRelModelImpl . ENTITY_CACHE_ENABLED , CPDefinitionOptionValueRelImpl . class , cpDefinitionOptionValueRel . getPrimaryKey ( ) ) == null ) { cacheResult ( cpDefinitionOptionValueRel ) ; } else { cpDefinitionOptionValueRel . resetOriginalValues ( ) ; } } }
Caches the cp definition option value rels in the entity cache if it is enabled .
133
18
31,507
@ Override public void clearCache ( ) { entityCache . clearCache ( CPDefinitionOptionValueRelImpl . class ) ; finderCache . clearCache ( FINDER_CLASS_NAME_ENTITY ) ; finderCache . clearCache ( FINDER_CLASS_NAME_LIST_WITH_PAGINATION ) ; finderCache . clearCache ( FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION ) ; }
Clears the cache for all cp definition option value rels .
101
13
31,508
@ Override public List < CPDefinitionOptionValueRel > findAll ( ) { return findAll ( QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ; }
Returns all the cp definition option value rels .
43
10
31,509
@ Indexable ( type = IndexableType . DELETE ) @ Override public CPDefinitionOptionRel deleteCPDefinitionOptionRel ( long CPDefinitionOptionRelId ) throws PortalException { return cpDefinitionOptionRelPersistence . remove ( CPDefinitionOptionRelId ) ; }
Deletes the cp definition option rel with the primary key from the database . Also notifies the appropriate model listeners .
65
23
31,510
@ Override public List < CPDefinitionOptionRel > getCPDefinitionOptionRelsByUuidAndCompanyId ( String uuid , long companyId , int start , int end , OrderByComparator < CPDefinitionOptionRel > orderByComparator ) { return cpDefinitionOptionRelPersistence . findByUuid_C ( uuid , companyId , start , end , orderByComparator ) ; }
Returns a range of cp definition option rels matching the UUID and company .
92
16
31,511
@ Override public < T > List < T > dynamicQuery ( DynamicQuery dynamicQuery , int start , int end ) { return commerceShipmentItemPersistence . findWithDynamicQuery ( dynamicQuery , start , end ) ; }
Performs a dynamic query on the database and returns a range of the matching rows .
48
17
31,512
@ Override public void cacheResult ( CommerceDiscount commerceDiscount ) { entityCache . putResult ( CommerceDiscountModelImpl . ENTITY_CACHE_ENABLED , CommerceDiscountImpl . class , commerceDiscount . getPrimaryKey ( ) , commerceDiscount ) ; finderCache . putResult ( FINDER_PATH_FETCH_BY_UUID_G , new Object [ ] { commerceDiscount . getUuid ( ) , commerceDiscount . getGroupId ( ) } , commerceDiscount ) ; commerceDiscount . resetOriginalValues ( ) ; }
Caches the commerce discount in the entity cache if it is enabled .
127
14
31,513
@ Override public void cacheResult ( List < CommerceDiscount > commerceDiscounts ) { for ( CommerceDiscount commerceDiscount : commerceDiscounts ) { if ( entityCache . getResult ( CommerceDiscountModelImpl . ENTITY_CACHE_ENABLED , CommerceDiscountImpl . class , commerceDiscount . getPrimaryKey ( ) ) == null ) { cacheResult ( commerceDiscount ) ; } else { commerceDiscount . resetOriginalValues ( ) ; } } }
Caches the commerce discounts in the entity cache if it is enabled .
105
14
31,514
@ Override public void clearCache ( ) { entityCache . clearCache ( CommerceDiscountImpl . class ) ; finderCache . clearCache ( FINDER_CLASS_NAME_ENTITY ) ; finderCache . clearCache ( FINDER_CLASS_NAME_LIST_WITH_PAGINATION ) ; finderCache . clearCache ( FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION ) ; }
Clears the cache for all commerce discounts .
97
9
31,515
@ Override public void clearCache ( CommerceDiscount commerceDiscount ) { entityCache . removeResult ( CommerceDiscountModelImpl . ENTITY_CACHE_ENABLED , CommerceDiscountImpl . class , commerceDiscount . getPrimaryKey ( ) ) ; finderCache . clearCache ( FINDER_CLASS_NAME_LIST_WITH_PAGINATION ) ; finderCache . clearCache ( FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION ) ; clearUniqueFindersCache ( ( CommerceDiscountModelImpl ) commerceDiscount , true ) ; }
Clears the cache for the commerce discount .
131
9
31,516
@ Override public List < CommerceDiscount > findAll ( ) { return findAll ( QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ; }
Returns all the commerce discounts .
39
6
31,517
public AuthorizationCodeTokenRequest newTokenRequest ( String authorizationCode ) { return new AuthorizationCodeTokenRequest ( transport , jsonFactory , new GenericUrl ( tokenServerEncodedUrl ) , authorizationCode ) . setClientAuthentication ( clientAuthentication ) . setRequestInitializer ( requestInitializer ) . setScopes ( scopes ) ; }
Returns a new instance of an authorization code token request based on the given authorization code .
70
17
31,518
@ SuppressWarnings ( "deprecation" ) public Credential createAndStoreCredential ( TokenResponse response , String userId ) throws IOException { Credential credential = newCredential ( userId ) . setFromTokenResponse ( response ) ; if ( credentialStore != null ) { credentialStore . store ( userId , credential ) ; } if ( credentialDataStore != null ) { credentialDataStore . set ( userId , new StoredCredential ( credential ) ) ; } if ( credentialCreatedListener != null ) { credentialCreatedListener . onCredentialCreated ( credential , response ) ; } return credential ; }
Creates a new credential for the given user ID based on the given token response and stores it in the credential store .
137
24
31,519
@ SuppressWarnings ( "deprecation" ) public Credential loadCredential ( String userId ) throws IOException { // No requests need to be performed when userId is not specified. if ( isNullOrEmpty ( userId ) ) { return null ; } if ( credentialDataStore == null && credentialStore == null ) { return null ; } Credential credential = newCredential ( userId ) ; if ( credentialDataStore != null ) { StoredCredential stored = credentialDataStore . get ( userId ) ; if ( stored == null ) { return null ; } credential . setAccessToken ( stored . getAccessToken ( ) ) ; credential . setRefreshToken ( stored . getRefreshToken ( ) ) ; credential . setExpirationTimeMilliseconds ( stored . getExpirationTimeMilliseconds ( ) ) ; } else if ( ! credentialStore . load ( userId , credential ) ) { return null ; } return credential ; }
Loads the credential of the given user ID from the credential store .
209
14
31,520
@ SuppressWarnings ( "deprecation" ) private Credential newCredential ( String userId ) { Credential . Builder builder = new Credential . Builder ( method ) . setTransport ( transport ) . setJsonFactory ( jsonFactory ) . setTokenServerEncodedUrl ( tokenServerEncodedUrl ) . setClientAuthentication ( clientAuthentication ) . setRequestInitializer ( requestInitializer ) . setClock ( clock ) ; if ( credentialDataStore != null ) { builder . addRefreshListener ( new DataStoreCredentialRefreshListener ( userId , credentialDataStore ) ) ; } else if ( credentialStore != null ) { builder . addRefreshListener ( new CredentialStoreRefreshListener ( userId , credentialStore ) ) ; } builder . getRefreshListeners ( ) . addAll ( refreshListeners ) ; return builder . build ( ) ; }
Returns a new credential instance based on the given user ID .
196
12
31,521
static final String getUserId ( ) { UserService userService = UserServiceFactory . getUserService ( ) ; User loggedIn = userService . getCurrentUser ( ) ; Preconditions . checkState ( loggedIn != null , "This servlet requires the user to be logged in." ) ; return loggedIn . getUserId ( ) ; }
Return the user id for the currently logged in user .
74
11
31,522
public final OAuthCredentialsResponse execute ( ) throws IOException { HttpRequestFactory requestFactory = transport . createRequestFactory ( ) ; HttpRequest request = requestFactory . buildRequest ( usePost ? HttpMethods . POST : HttpMethods . GET , this , null ) ; createParameters ( ) . intercept ( request ) ; HttpResponse response = request . execute ( ) ; response . setContentLoggingLimit ( 0 ) ; OAuthCredentialsResponse oauthResponse = new OAuthCredentialsResponse ( ) ; UrlEncodedParser . parse ( response . parseAsString ( ) , oauthResponse ) ; return oauthResponse ; }
Executes the HTTP request for a temporary or long - lived token .
140
14
31,523
public OAuthParameters createParameters ( ) { OAuthParameters result = new OAuthParameters ( ) ; result . consumerKey = consumerKey ; result . signer = signer ; return result ; }
Returns a new instance of the OAuth authentication provider . Subclasses may override by calling this super implementation and then adding OAuth parameters .
41
27
31,524
public TokenRequest setTokenServerUrl ( GenericUrl tokenServerUrl ) { this . tokenServerUrl = tokenServerUrl ; Preconditions . checkArgument ( tokenServerUrl . getFragment ( ) == null ) ; return this ; }
Sets the token server URL .
50
7
31,525
public final HttpResponse executeUnparsed ( ) throws IOException { // must set clientAuthentication as last execute interceptor in case it needs to sign request HttpRequestFactory requestFactory = transport . createRequestFactory ( new HttpRequestInitializer ( ) { public void initialize ( HttpRequest request ) throws IOException { if ( requestInitializer != null ) { requestInitializer . initialize ( request ) ; } final HttpExecuteInterceptor interceptor = request . getInterceptor ( ) ; request . setInterceptor ( new HttpExecuteInterceptor ( ) { public void intercept ( HttpRequest request ) throws IOException { if ( interceptor != null ) { interceptor . intercept ( request ) ; } if ( clientAuthentication != null ) { clientAuthentication . intercept ( request ) ; } } } ) ; } } ) ; // make request HttpRequest request = requestFactory . buildPostRequest ( tokenServerUrl , new UrlEncodedContent ( this ) ) ; request . setParser ( new JsonObjectParser ( jsonFactory ) ) ; request . setThrowExceptionOnExecuteError ( false ) ; HttpResponse response = request . execute ( ) ; if ( response . isSuccessStatusCode ( ) ) { return response ; } throw TokenResponseException . from ( jsonFactory , response ) ; }
Executes request for an access token and returns the HTTP response .
279
13
31,526
public Credential setAccessToken ( String accessToken ) { lock . lock ( ) ; try { this . accessToken = accessToken ; } finally { lock . unlock ( ) ; } return this ; }
Sets the access token .
43
6
31,527
public Credential setRefreshToken ( String refreshToken ) { lock . lock ( ) ; try { if ( refreshToken != null ) { Preconditions . checkArgument ( jsonFactory != null && transport != null && clientAuthentication != null && tokenServerEncodedUrl != null , "Please use the Builder and call setJsonFactory, setTransport, setClientAuthentication" + " and setTokenServerUrl/setTokenServerEncodedUrl" ) ; } this . refreshToken = refreshToken ; } finally { lock . unlock ( ) ; } return this ; }
Sets the refresh token .
122
6
31,528
public final boolean refreshToken ( ) throws IOException { lock . lock ( ) ; try { try { TokenResponse tokenResponse = executeRefreshToken ( ) ; if ( tokenResponse != null ) { setFromTokenResponse ( tokenResponse ) ; for ( CredentialRefreshListener refreshListener : refreshListeners ) { refreshListener . onTokenResponse ( this , tokenResponse ) ; } return true ; } } catch ( TokenResponseException e ) { boolean statusCode4xx = 400 <= e . getStatusCode ( ) && e . getStatusCode ( ) < 500 ; // check if it is a normal error response if ( e . getDetails ( ) != null && statusCode4xx ) { // We were unable to get a new access token (e.g. it may have been revoked), we must now // indicate that our current token is invalid. setAccessToken ( null ) ; setExpiresInSeconds ( null ) ; } for ( CredentialRefreshListener refreshListener : refreshListeners ) { refreshListener . onTokenErrorResponse ( this , e . getDetails ( ) ) ; } if ( statusCode4xx ) { throw e ; } } return false ; } finally { lock . unlock ( ) ; } }
Request a new access token from the authorization endpoint .
258
10
31,529
protected TokenResponse executeRefreshToken ( ) throws IOException { if ( refreshToken == null ) { return null ; } return new RefreshTokenRequest ( transport , jsonFactory , new GenericUrl ( tokenServerEncodedUrl ) , refreshToken ) . setClientAuthentication ( clientAuthentication ) . setRequestInitializer ( requestInitializer ) . execute ( ) ; }
Executes a request for new credentials from the token server .
76
12
31,530
private void startAuthFlow ( HttpServletResponse resp , PersistenceManager pm , ThreeLeggedFlow oauthFlow ) throws IOException { pm . makePersistent ( oauthFlow ) ; String authorizationUrl = oauthFlow . getAuthorizationUrl ( ) ; resp . sendRedirect ( authorizationUrl ) ; }
Start the auth flow . Don t run any code after this method that will change the response object .
67
20
31,531
protected Credential getCredential ( HttpServletRequest req ) { Credential cred = ( Credential ) req . getAttribute ( AUTH_CREDENTIAL ) ; return cred ; }
Fetch a credential associated with this request .
44
9
31,532
private void ringWrite ( long position , byte [ ] buffer , int offset , int count ) throws IOException { position = wrapPosition ( position ) ; if ( position + count <= fileLength ) { raf . seek ( position ) ; raf . write ( buffer , offset , count ) ; } else { // The write overlaps the EOF. // # of bytes to write before the EOF. Guaranteed to be less than Integer.MAX_VALUE. int beforeEof = ( int ) ( fileLength - position ) ; raf . seek ( position ) ; raf . write ( buffer , offset , beforeEof ) ; raf . seek ( headerLength ) ; raf . write ( buffer , offset + beforeEof , count - beforeEof ) ; } }
Writes count bytes from buffer to position in file . Automatically wraps write if position is past the end of the file or if buffer overlaps it .
164
31
31,533
private void expandIfNecessary ( long dataLength ) throws IOException { long elementLength = Element . HEADER_LENGTH + dataLength ; long remainingBytes = remainingBytes ( ) ; if ( remainingBytes >= elementLength ) return ; // Expand. long previousLength = fileLength ; long newLength ; // Double the length until we can fit the new data. do { remainingBytes += previousLength ; newLength = previousLength << 1 ; previousLength = newLength ; } while ( remainingBytes < elementLength ) ; setLength ( newLength ) ; // Calculate the position of the tail end of the data in the ring buffer long endOfLastElement = wrapPosition ( last . position + Element . HEADER_LENGTH + last . length ) ; long count = 0 ; // If the buffer is split, we need to make it contiguous if ( endOfLastElement <= first . position ) { FileChannel channel = raf . getChannel ( ) ; channel . position ( fileLength ) ; // destination position count = endOfLastElement - headerLength ; if ( channel . transferTo ( headerLength , count , channel ) != count ) { throw new AssertionError ( "Copied insufficient number of bytes!" ) ; } } // Commit the expansion. if ( last . position < first . position ) { long newLastPosition = fileLength + last . position - headerLength ; writeHeader ( newLength , elementCount , first . position , newLastPosition ) ; last = new Element ( newLastPosition , last . length ) ; } else { writeHeader ( newLength , elementCount , first . position , last . position ) ; } fileLength = newLength ; if ( zero ) { ringErase ( headerLength , count ) ; } }
If necessary expands the file to accommodate an additional element of the given length .
366
15
31,534
@ SuppressWarnings ( { "unchecked" , "TypeParameterUnusedInFormals" } ) static < T extends Throwable > T getSneakyThrowable ( Throwable t ) throws T { throw ( T ) t ; }
Use this to throw checked exceptions from iterator methods that do not declare that they throw checked exceptions .
53
19
31,535
public float [ ] t1 ( float [ ] z , int k ) { float [ ] result = new float [ z . length ] ; System . arraycopy ( z , 0 , result , 0 , k ) ; for ( int i = k ; i < z . length ; i ++ ) { result [ i ] = ( new Transformations ( ) ) . sLinear ( z [ i ] , ( float ) 0.35 ) ; } return result ; }
WFG3 t1 transformation
97
6
31,536
public float [ ] t2 ( float [ ] z , int k ) { float [ ] result = new float [ z . length ] ; System . arraycopy ( z , 0 , result , 0 , k ) ; int l = z . length - k ; for ( int i = k + 1 ; i <= k + l / 2 ; i ++ ) { int head = k + 2 * ( i - k ) - 1 ; int tail = k + 2 * ( i - k ) ; float [ ] subZ = subVector ( z , head - 1 , tail - 1 ) ; result [ i - 1 ] = ( new Transformations ( ) ) . rNonsep ( subZ , 2 ) ; } return result ; }
WFG3 t2 transformation
154
6
31,537
public void removeDuplicatedAlgorithms ( ) { List < ExperimentAlgorithm < S , Result > > algorithmList = new ArrayList <> ( ) ; HashSet < String > algorithmTagList = new HashSet <> ( ) ; getAlgorithmList ( ) . removeIf ( alg -> ! algorithmTagList . add ( alg . getAlgorithmTag ( ) ) ) ; }
The list of algorithms contain an algorithm instance per problem . This is not convenient for calculating statistical data because a same algorithm will appear many times . This method remove duplicated algorithms and leave only an instance of each one .
84
43
31,538
protected void initializeUniformWeight ( ) { if ( ( problem . getNumberOfObjectives ( ) == 2 ) && ( populationSize <= 300 ) ) { for ( int n = 0 ; n < populationSize ; n ++ ) { double a = 1.0 * n / ( populationSize - 1 ) ; lambda [ n ] [ 0 ] = a ; lambda [ n ] [ 1 ] = 1 - a ; } } else { String dataFileName ; dataFileName = "W" + problem . getNumberOfObjectives ( ) + "D_" + populationSize + ".dat" ; try { // String path = // Paths.get(VectorFileUtils.class.getClassLoader().getResource(filePath).toURI()).toString // (); InputStream in = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( dataDirectory + "/" + dataFileName ) ; InputStreamReader isr = new InputStreamReader ( in ) ; BufferedReader br = new BufferedReader ( isr ) ; int i = 0 ; int j = 0 ; String aux = br . readLine ( ) ; while ( aux != null ) { StringTokenizer st = new StringTokenizer ( aux ) ; j = 0 ; while ( st . hasMoreTokens ( ) ) { double value = new Double ( st . nextToken ( ) ) ; lambda [ i ] [ j ] = value ; j ++ ; } aux = br . readLine ( ) ; i ++ ; } br . close ( ) ; } catch ( Exception e ) { throw new JMetalException ( "initializeUniformWeight: failed when reading for file: " + dataDirectory + "/" + dataFileName , e ) ; } } }
Initialize weight vectors
368
4
31,539
@ SuppressWarnings ( "unchecked" ) protected void updateNeighborhood ( S individual , int subProblemId , NeighborType neighborType ) throws JMetalException { int size ; int time ; time = 0 ; if ( neighborType == NeighborType . NEIGHBOR ) { size = neighborhood [ subProblemId ] . length ; } else { size = population . size ( ) ; } int [ ] perm = new int [ size ] ; MOEADUtils . randomPermutation ( perm , size ) ; for ( int i = 0 ; i < size ; i ++ ) { int k ; if ( neighborType == NeighborType . NEIGHBOR ) { k = neighborhood [ subProblemId ] [ perm [ i ] ] ; } else { k = perm [ i ] ; } double f1 , f2 ; f1 = fitnessFunction ( population . get ( k ) , lambda [ k ] ) ; f2 = fitnessFunction ( individual , lambda [ k ] ) ; if ( f2 < f1 ) { population . set ( k , ( S ) individual . copy ( ) ) ; time ++ ; } if ( time >= maximumNumberOfReplacedSolutions ) { return ; } } }
Update neighborhood method
256
3
31,540
public void initPopulation ( ) { for ( int i = 0 ; i < populationSize ; i ++ ) { S newSolution = problem . createSolution ( ) ; problem . evaluate ( newSolution ) ; evaluations ++ ; population . add ( newSolution ) ; subregionIdx [ i ] [ i ] = 1 ; } }
Initialize the population
68
4
31,541
public double sumFitness ( int location ) { double sum = 0 ; for ( int i = 0 ; i < populationSize ; i ++ ) { if ( subregionIdx [ location ] [ i ] == 1 ) { sum = sum + fitnessFunction ( population . get ( i ) , lambda [ location ] ) ; } } return sum ; }
calculate the sum of fitnesses of solutions in the location subregion
73
15
31,542
public void deleteCrowdIndiv_same ( int crowdIdx , int nicheCount , double indivFitness , S indiv ) { // find the solution indices within this crowdIdx subregion ArrayList < Integer > indList = new ArrayList <> ( ) ; for ( int i = 0 ; i < populationSize ; i ++ ) { if ( subregionIdx [ crowdIdx ] [ i ] == 1 ) { indList . add ( i ) ; } } // find the solution with the worst fitness value int listSize = indList . size ( ) ; int worstIdx = indList . get ( 0 ) ; double maxFitness = fitnessFunction ( population . get ( worstIdx ) , lambda [ crowdIdx ] ) ; for ( int i = 1 ; i < listSize ; i ++ ) { int curIdx = indList . get ( i ) ; double curFitness = fitnessFunction ( population . get ( curIdx ) , lambda [ crowdIdx ] ) ; if ( curFitness > maxFitness ) { worstIdx = curIdx ; maxFitness = curFitness ; } } // if indiv has a better fitness, use indiv to replace the worst one if ( indivFitness < maxFitness ) { replace ( worstIdx , indiv ) ; } }
delete one solution from the most crowded subregion which is indiv s subregion . Compare indiv s fitness value and the worst one in this subregion
284
31
31,543
public void deleteCrowdIndiv_diff ( int crowdIdx , int curLocation , int nicheCount , S indiv ) { // find the solution indices within this crowdIdx subregion ArrayList < Integer > indList = new ArrayList <> ( ) ; for ( int i = 0 ; i < populationSize ; i ++ ) { if ( subregionIdx [ crowdIdx ] [ i ] == 1 ) { indList . add ( i ) ; } } // find the solution with the worst fitness value int worstIdx = indList . get ( 0 ) ; double maxFitness = fitnessFunction ( population . get ( worstIdx ) , lambda [ crowdIdx ] ) ; for ( int i = 1 ; i < nicheCount ; i ++ ) { int curIdx = indList . get ( i ) ; double curFitness = fitnessFunction ( population . get ( curIdx ) , lambda [ crowdIdx ] ) ; if ( curFitness > maxFitness ) { worstIdx = curIdx ; maxFitness = curFitness ; } } // use indiv to replace the worst one replace ( worstIdx , indiv ) ; subregionIdx [ crowdIdx ] [ worstIdx ] = 0 ; subregionIdx [ curLocation ] [ worstIdx ] = 1 ; }
delete one solution from the most crowded subregion which is different from indiv s subregion . just use indiv to replace the worst solution in that subregion
283
32
31,544
public int countOnes ( int location ) { int count = 0 ; for ( int i = 0 ; i < populationSize ; i ++ ) { if ( subregionIdx [ location ] [ i ] == 1 ) { count ++ ; } } return count ; }
Count the number of 1s in the location th subregion
56
12
31,545
public int countRankOnes ( int location ) { int count = 0 ; for ( int i = 0 ; i < populationSize ; i ++ ) { if ( rankIdx [ location ] [ i ] == 1 ) { count ++ ; } } return count ; }
count the number of 1s in a row of rank matrix
56
12
31,546
public int findPosition ( S indiv ) { for ( int i = 0 ; i < populationSize ; i ++ ) { if ( indiv . equals ( population . get ( i ) ) ) { return i ; } } return - 1 ; }
find the index of the solution indiv in the population
52
11
31,547
public int findRegion ( int idx ) { for ( int i = 0 ; i < populationSize ; i ++ ) { if ( subregionIdx [ i ] [ idx ] == 1 ) { return i ; } } return - 1 ; }
find the subregion of the idx th solution in the population
53
13
31,548
public void setLocation ( S indiv , double [ ] z_ , double [ ] nz_ ) { int minIdx ; double distance , minDist ; minIdx = 0 ; distance = calculateDistance2 ( indiv , lambda [ 0 ] , z_ , nz_ ) ; minDist = distance ; for ( int i = 1 ; i < populationSize ; i ++ ) { distance = calculateDistance2 ( indiv , lambda [ i ] , z_ , nz_ ) ; if ( distance < minDist ) { minIdx = i ; minDist = distance ; } } //indiv.setRegion(minIdx); indiv . setAttribute ( "region" , minIdx ) ; //indiv.Set_associateDist(minDist); // indiv.setAttribute(ATTRIBUTES.DIST, minDist); }
Set the location of a solution based on the orthogonal distance
185
13
31,549
public double innerproduct ( double [ ] vec1 , double [ ] vec2 ) { double sum = 0 ; for ( int i = 0 ; i < vec1 . length ; i ++ ) { sum += vec1 [ i ] * vec2 [ i ] ; } return sum ; }
Calculate the dot product of two vectors
60
9
31,550
public double norm_vector ( double [ ] z ) { double sum = 0 ; for ( int i = 0 ; i < problem . getNumberOfObjectives ( ) ; i ++ ) { sum += z [ i ] * z [ i ] ; } return Math . sqrt ( sum ) ; }
Calculate the norm of the vector
63
8
31,551
private double epsilon ( Front front , Front referenceFront ) throws JMetalException { double eps , epsJ = 0.0 , epsK = 0.0 , epsTemp ; int numberOfObjectives = front . getPointDimensions ( ) ; eps = Double . MIN_VALUE ; for ( int i = 0 ; i < referenceFront . getNumberOfPoints ( ) ; i ++ ) { for ( int j = 0 ; j < front . getNumberOfPoints ( ) ; j ++ ) { for ( int k = 0 ; k < numberOfObjectives ; k ++ ) { epsTemp = front . getPoint ( j ) . getValue ( k ) - referenceFront . getPoint ( i ) . getValue ( k ) ; if ( k == 0 ) { epsK = epsTemp ; } else if ( epsK < epsTemp ) { epsK = epsTemp ; } } if ( j == 0 ) { epsJ = epsK ; } else if ( epsJ > epsK ) { epsJ = epsK ; } } if ( i == 0 ) { eps = epsJ ; } else if ( eps < epsJ ) { eps = epsJ ; } } return eps ; }
Returns the value of the epsilon indicator .
278
10
31,552
protected double evalH ( double f , double g ) { double h ; h = 1.0 - Math . sqrt ( f / g ) - ( f / g ) * Math . sin ( 10.0 * Math . PI * f ) ; return h ; }
Returns the value of the ZDT3 function H .
56
11
31,553
public boolean prefers ( int x , int y , int [ ] womanPref , int size ) { for ( int i = 0 ; i < size ; i ++ ) { int pref = womanPref [ i ] ; if ( pref == x ) { return true ; } if ( pref == y ) { return false ; } } // this should never happen. System . out . println ( "Error in womanPref list!" ) ; return false ; }
Returns true in case that a given woman prefers x to y .
92
13
31,554
@ Override public void referenceSetUpdate ( DoubleSolution solution ) { if ( refSet1Test ( solution ) ) { for ( DoubleSolution solutionInRefSet2 : referenceSet2 ) { double aux = SolutionUtils . distanceBetweenSolutionsInObjectiveSpace ( solution , solutionInRefSet2 ) ; DoubleSolution auxSolution = solutionInRefSet2 ; if ( aux < distanceToSolutionListAttribute . getAttribute ( auxSolution ) ) { distanceToSolutionListAttribute . setAttribute ( auxSolution , aux ) ; } } } else { refSet2Test ( solution ) ; } }
Update the reference set with a new solution
124
8
31,555
public void buildNewReferenceSet1 ( ) { DoubleSolution individual ; strengthRawFitness . computeDensityEstimator ( getPopulation ( ) ) ; Collections . sort ( getPopulation ( ) , fitnessComparator ) ; for ( int i = 0 ; i < referenceSet1Size ; i ++ ) { individual = getPopulation ( ) . get ( 0 ) ; getPopulation ( ) . remove ( 0 ) ; marked . setAttribute ( individual , false ) ; referenceSet1 . add ( individual ) ; } }
Build the referenceSet1 by moving the best referenceSet1Size individuals according to a fitness comparator from the population to the referenceSet1
107
28
31,556
public void buildNewReferenceSet2 ( ) { for ( int i = 0 ; i < getPopulation ( ) . size ( ) ; i ++ ) { DoubleSolution individual = getPopulation ( ) . get ( i ) ; double distanceAux = SolutionUtils . distanceToSolutionListInSolutionSpace ( individual , referenceSet1 ) ; distanceToSolutionListAttribute . setAttribute ( individual , distanceAux ) ; } int size = referenceSet2Size ; if ( getPopulation ( ) . size ( ) < referenceSet2Size ) { size = getPopulation ( ) . size ( ) ; } for ( int i = 0 ; i < size ; i ++ ) { // Find the maximumMinimumDistanceToPopulation double maxMinimum = 0.0 ; int index = 0 ; for ( int j = 0 ; j < getPopulation ( ) . size ( ) ; j ++ ) { DoubleSolution auxSolution = getPopulation ( ) . get ( j ) ; if ( distanceToSolutionListAttribute . getAttribute ( auxSolution ) > maxMinimum ) { maxMinimum = distanceToSolutionListAttribute . getAttribute ( auxSolution ) ; index = j ; } } DoubleSolution individual = getPopulation ( ) . get ( index ) ; getPopulation ( ) . remove ( index ) ; // Update distances to REFSET in population for ( int j = 0 ; j < getPopulation ( ) . size ( ) ; j ++ ) { double aux = SolutionUtils . distanceBetweenSolutionsInObjectiveSpace ( getPopulation ( ) . get ( j ) , individual ) ; if ( aux < distanceToSolutionListAttribute . getAttribute ( individual ) ) { DoubleSolution auxSolution = getPopulation ( ) . get ( j ) ; distanceToSolutionListAttribute . setAttribute ( auxSolution , aux ) ; } } // Insert the individual into REFSET2 marked . setAttribute ( individual , false ) ; referenceSet2 . add ( individual ) ; // Update distances in REFSET2 for ( int j = 0 ; j < referenceSet2 . size ( ) ; j ++ ) { for ( int k = 0 ; k < referenceSet2 . size ( ) ; k ++ ) { if ( i != j ) { double aux = SolutionUtils . distanceBetweenSolutionsInObjectiveSpace ( referenceSet2 . get ( j ) , referenceSet2 . get ( k ) ) ; DoubleSolution auxSolution = referenceSet2 . get ( j ) ; if ( aux < distanceToSolutionListAttribute . getAttribute ( auxSolution ) ) { distanceToSolutionListAttribute . setAttribute ( auxSolution , aux ) ; } } } } } }
Build the referenceSet2 by moving to it the most diverse referenceSet2Size individuals from the population in respect to the referenceSet1 .
544
28
31,557
@ Override public List < List < DoubleSolution > > subsetGeneration ( ) { List < List < DoubleSolution >> solutionGroupsList ; solutionGroupsList = generatePairsFromSolutionList ( referenceSet1 ) ; solutionGroupsList . addAll ( generatePairsFromSolutionList ( referenceSet2 ) ) ; return solutionGroupsList ; }
Subset generation method
75
4
31,558
public List < List < DoubleSolution > > generatePairsFromSolutionList ( List < DoubleSolution > solutionList ) { List < List < DoubleSolution >> subset = new ArrayList <> ( ) ; for ( int i = 0 ; i < solutionList . size ( ) ; i ++ ) { DoubleSolution solution1 = solutionList . get ( i ) ; for ( int j = i + 1 ; j < solutionList . size ( ) ; j ++ ) { DoubleSolution solution2 = solutionList . get ( j ) ; if ( ! marked . getAttribute ( solution1 ) || ! marked . getAttribute ( solution2 ) ) { List < DoubleSolution > pair = new ArrayList <> ( 2 ) ; pair . add ( solution1 ) ; pair . add ( solution2 ) ; subset . add ( pair ) ; marked . setAttribute ( solutionList . get ( i ) , true ) ; marked . setAttribute ( solutionList . get ( j ) , true ) ; } } } return subset ; }
Generate all pair combinations of the referenceSet1
211
10
31,559
private void resetIndicatorFiles ( ) { for ( GenericIndicator < S > indicator : experiment . getIndicatorList ( ) ) { for ( ExperimentAlgorithm < ? , Result > algorithm : experiment . getAlgorithmList ( ) ) { for ( ExperimentProblem < ? > problem : experiment . getProblemList ( ) ) { String algorithmDirectory ; algorithmDirectory = experiment . getExperimentBaseDirectory ( ) + "/data/" + algorithm . getAlgorithmTag ( ) ; String problemDirectory = algorithmDirectory + "/" + problem . getTag ( ) ; String qualityIndicatorFile = problemDirectory + "/" + indicator . getName ( ) ; resetFile ( qualityIndicatorFile ) ; } } } }
Deletes the files containing the indicator values if the exist .
148
12
31,560
private void resetFile ( String file ) { File f = new File ( file ) ; if ( f . exists ( ) ) { JMetalLogger . logger . info ( "Already existing file " + file ) ; if ( f . isDirectory ( ) ) { JMetalLogger . logger . info ( "Deleting directory " + file ) ; if ( f . delete ( ) ) { JMetalLogger . logger . info ( "Directory successfully deleted." ) ; } else { JMetalLogger . logger . info ( "Error deleting directory." ) ; } } else { JMetalLogger . logger . info ( "Deleting file " + file ) ; if ( f . delete ( ) ) { JMetalLogger . logger . info ( "File successfully deleted." ) ; } else { JMetalLogger . logger . info ( "Error deleting file." ) ; } } } else { JMetalLogger . logger . info ( "File " + file + " does NOT exist." ) ; } }
Deletes a file or directory if it does exist
214
10
31,561
public double [ ] [ ] lines_of_polygon ( double [ ] [ ] p ) { double [ ] [ ] c9 = new double [ p . length ] [ 3 ] ; for ( int i = 0 ; i < p . length - 1 ; i ++ ) { // evaluate formula of the straight line l1,...,m-1 c9 [ i ] = line_of_twoP ( p [ i ] , p [ i + 1 ] ) ; } // evaluate formula of the straight line lm c9 [ p . length - 1 ] = line_of_twoP ( p [ p . length - 1 ] , p [ 0 ] ) ; return c9 ; }
given vertexes evaluate the straight lines of a polygon
146
11
31,562
public static double generV ( double lb , double ub ) { double p ; p = JMetalRandom . getInstance ( ) . nextDouble ( ) * ( ub - lb ) + lb ; return p ; }
generate a random variable with boundary lb ub
44
9
31,563
public void doMutation ( double probability , DoubleSolution solution ) { for ( int i = 0 ; i < solution . getNumberOfVariables ( ) ; i ++ ) { if ( randomGenenerator . getRandomValue ( ) < probability ) { double rand = randomGenenerator . getRandomValue ( ) ; double tmp = ( rand - 0.5 ) * perturbation ; tmp += solution . getVariableValue ( i ) ; if ( tmp < solution . getLowerBound ( i ) ) { tmp = solution . getLowerBound ( i ) ; } else if ( tmp > solution . getUpperBound ( i ) ) { tmp = solution . getUpperBound ( i ) ; } solution . setVariableValue ( i , tmp ) ; } } }
Perform the operation
162
4
31,564
private double evalG ( DoubleSolution solution ) { double g = 0.0 ; for ( int i = 2 ; i < solution . getNumberOfVariables ( ) ; i ++ ) { double t = solution . getVariableValue ( i ) - solution . getVariableValue ( 0 ) * solution . getVariableValue ( 1 ) ; g += - 0.9 * t * t + Math . pow ( Math . abs ( t ) , 0.6 ) ; } g = 2 * Math . sin ( Math . PI * solution . getVariableValue ( 0 ) ) * g ; return g ; }
Returns the value of the MOP6 function G .
126
11
31,565
public void add ( List < Double > maxs ) { List < Double > aux = new ArrayList <> ( this . numberOfObjectives ) ; aux . addAll ( maxs ) ; this . history . add ( aux ) ; if ( history . size ( ) > MAX_LENGHT ) history . remove ( 0 ) ; }
Adds a new vector of maxs values to the history . The method ensures that only the newest MAX_LENGTH vectors will be kept in the history
72
30
31,566
public List < Double > mean ( ) { List < Double > result = new ArrayList <> ( this . numberOfObjectives ) ; for ( int i = 0 ; i < this . numberOfObjectives ; i ++ ) result . ( 0.0 ) ; for ( List < Double > historyMember : this . history ) for ( int i = 0 ; i < this . numberOfObjectives ; i ++ ) result . set ( i , result . get ( i ) + historyMember . get ( i ) ) ; for ( int i = 0 ; i < this . numberOfObjectives ; i ++ ) result . set ( i , result . get ( i ) / ( double ) this . history . size ( ) ) ; return result ; }
Returns the mean of the values contained in the history
158
10
31,567
private static < S extends Solution < ? > > void setScalarizationValue ( S solution , double scalarizationValue ) { solution . setAttribute ( new ScalarizationValue < S > ( ) . getAttributeIdentifier ( ) , scalarizationValue ) ; }
Sets the scalarization value of a solution . Used for for simplified static access .
58
18
31,568
private static double [ ] toArray ( List < Double > list ) { double [ ] values = new double [ list . size ( ) ] ; for ( int i = 0 ; i < values . length ; i ++ ) { values [ i ] = list . get ( i ) ; } return values ; }
Method for turning a list of doubles to an array .
64
11
31,569
private static < S extends Solution < ? > > double [ ] getIdealValues ( List < S > solutionsList ) { ArrayFront front = new ArrayFront ( solutionsList ) ; FrontExtremeValues extremeValues = new FrontExtremeValues ( ) ; List < Double > list = extremeValues . findLowestValues ( front ) ; return toArray ( list ) ; }
Computes the ideal point based on a list of solutions
76
11
31,570
private static < S extends Solution < ? > > double [ ] getNadirValues ( List < S > solutionsList ) { ArrayFront front = new ArrayFront ( solutionsList ) ; FrontExtremeValues extremeValues = new FrontExtremeValues ( ) ; List < Double > list = extremeValues . findHighestValues ( front ) ; return toArray ( list ) ; }
Computes the nadir point based on a list of solutions
77
13
31,571
private static < S extends Solution < ? > > double [ ] [ ] getExtremePoints ( List < S > solutionsList ) { // One extreme point for each objective double [ ] [ ] extremePoints = new double [ solutionsList . get ( 0 ) . getNumberOfObjectives ( ) ] [ ] ; for ( int i = 0 ; i < extremePoints . length ; i ++ ) { S extreme = Collections . min ( solutionsList , new AchievementScalarizationComparator < S > ( i ) ) ; extremePoints [ i ] = new double [ extreme . getNumberOfObjectives ( ) ] ; for ( int j = 0 ; j < extremePoints . length ; j ++ ) { extremePoints [ i ] [ j ] = extreme . getObjective ( j ) ; } } return extremePoints ; }
Computes the extreme points on achievement scalarization values
171
11
31,572
public static < S extends Solution < ? > > void sumOfObjectives ( List < S > solutionsList ) { for ( S solution : solutionsList ) { double sum = solution . getObjective ( 0 ) ; for ( int i = 1 ; i < solution . getNumberOfObjectives ( ) ; i ++ ) { sum += solution . getObjective ( i ) ; } setScalarizationValue ( solution , sum ) ; } }
Scalarization values is computed by summing objective values .
94
13
31,573
public static < S extends Solution < ? > > void weightedSum ( List < S > solutionsList , double [ ] weights ) { for ( S solution : solutionsList ) { double sum = weights [ 0 ] * solution . getObjective ( 0 ) ; for ( int i = 1 ; i < solution . getNumberOfObjectives ( ) ; i ++ ) { sum += weights [ i ] * solution . getObjective ( i ) ; } setScalarizationValue ( solution , sum ) ; } }
Objective values are multiplied by weights and summed . Weights should always be positive .
107
17
31,574
public static < S extends Solution < ? > > void productOfObjectives ( List < S > solutionsList ) { for ( S solution : solutionsList ) { double product = solution . getObjective ( 0 ) ; for ( int i = 1 ; i < solution . getNumberOfObjectives ( ) ; i ++ ) { product *= solution . getObjective ( i ) ; } setScalarizationValue ( solution , product ) ; } }
Objective values are multiplied .
95
6
31,575
public static < S extends Solution < ? > > void weightedProduct ( List < S > solutionsList , double [ ] weights ) { for ( S solution : solutionsList ) { double product = Math . pow ( solution . getObjective ( 0 ) , weights [ 0 ] ) ; for ( int i = 1 ; i < solution . getNumberOfObjectives ( ) ; i ++ ) { product *= Math . pow ( solution . getObjective ( i ) , weights [ i ] ) ; } setScalarizationValue ( solution , product ) ; } }
Objectives are exponentiated by a positive weight and afterwards multiplied .
118
13
31,576
public static < S extends Solution < ? > > void chebyshev ( List < S > solutionsList ) { chebyshev ( solutionsList , getIdealValues ( solutionsList ) ) ; }
Scalarization values based on the Chebyshev function . The ideal point is computed from the list of solutions .
43
25
31,577
public static < S extends Solution < ? > > void weightedChebyshev ( List < S > solutionsList , double [ ] weights ) { weightedChebyshev ( solutionsList , getIdealValues ( solutionsList ) , weights ) ; }
Chebyhsev function with weighted objectives .
52
10
31,578
public static < S extends Solution < ? > > void chebyshev ( List < S > solutionsList , double [ ] idealValues ) { for ( S solution : solutionsList ) { double max = solution . getObjective ( 0 ) - idealValues [ 0 ] ; for ( int i = 1 ; i < solution . getNumberOfObjectives ( ) ; i ++ ) { max = Math . max ( max , solution . getObjective ( i ) - idealValues [ i ] ) ; } setScalarizationValue ( solution , max ) ; } }
Scalarization values based on the Chebyshev function .
119
14
31,579
public static < S extends Solution < ? > > void nash ( List < S > solutionsList ) { nash ( solutionsList , getNadirValues ( solutionsList ) ) ; }
Scalarization values based on the Nash bargaining solution . The disagreement point is computed based on the list of solutions .
40
24
31,580
public static < S extends Solution < ? > > void nash ( List < S > solutionsList , double [ ] nadirValues ) { for ( S solution : solutionsList ) { double nash = nadirValues [ 0 ] - solution . getObjective ( 0 ) ; for ( int i = 1 ; i < nadirValues . length ; i ++ ) { nash *= ( nadirValues [ i ] - solution . getObjective ( i ) ) ; } // The Nash bargaining solution is originally maximized. To conform // with minimization the bargaining value is negated. setScalarizationValue ( solution , - nash ) ; } }
Scalarization values based on the Nash bargaining solution .
143
12
31,581
public static < S extends Solution < ? > > void uniform ( List < S > solutionsList ) { for ( S solution : solutionsList ) { setScalarizationValue ( solution , 1.0 ) ; } }
Uniform preferences . Each solution is assigned a scalarization value of 1 . 0 .
46
18
31,582
public float [ ] t2 ( float [ ] z , int k ) { float [ ] result = new float [ z . length ] ; System . arraycopy ( z , 0 , result , 0 , k ) ; for ( int i = k ; i < z . length ; i ++ ) { result [ i ] = ( new Transformations ( ) ) . bFlat ( z [ i ] , ( float ) 0.8 , ( float ) 0.75 , ( float ) 0.85 ) ; } return result ; }
WFG1 t2 transformation
111
6
31,583
public float [ ] t3 ( float [ ] z ) throws JMetalException { float [ ] result = new float [ z . length ] ; for ( int i = 0 ; i < z . length ; i ++ ) { result [ i ] = ( new Transformations ( ) ) . bPoly ( z [ i ] , ( float ) 0.02 ) ; } return result ; }
WFG1 t3 transformation
81
6
31,584
public float [ ] t4 ( float [ ] z , int k , int M ) { float [ ] result = new float [ M ] ; float [ ] w = new float [ z . length ] ; for ( int i = 0 ; i < z . length ; i ++ ) { w [ i ] = ( float ) 2.0 * ( i + 1 ) ; } for ( int i = 1 ; i <= M - 1 ; i ++ ) { int head = ( i - 1 ) * k / ( M - 1 ) + 1 ; int tail = i * k / ( M - 1 ) ; float [ ] subZ = subVector ( z , head - 1 , tail - 1 ) ; float [ ] subW = subVector ( w , head - 1 , tail - 1 ) ; result [ i - 1 ] = ( new Transformations ( ) ) . rSum ( subZ , subW ) ; } int head = k + 1 - 1 ; int tail = z . length - 1 ; float [ ] subZ = subVector ( z , head , tail ) ; float [ ] subW = subVector ( w , head , tail ) ; result [ M - 1 ] = ( new Transformations ( ) ) . rSum ( subZ , subW ) ; return result ; }
WFG1 t4 transformation
273
6
31,585
public static boolean validate ( double [ ] [ ] weights , int numberOfComponents ) { int i ; boolean correct ; correct = ( weights != null && weights . length > 0 ) ; i = 0 ; while ( correct && i < weights . length ) { correct = ( weights [ i ] . length == numberOfComponents ) ; i ++ ; } return correct ; }
Validate if the number of components of all weight vectors has the expected dimensionality .
78
17
31,586
public static double [ ] [ ] initializeUniformlyInTwoDimensions ( double epsilon , int numberOfWeights ) { double [ ] [ ] weights = new double [ numberOfWeights ] [ 2 ] ; int indexOfWeight ; double w , jump ; jump = ( 1 - ( 2 * epsilon ) ) / ( numberOfWeights - 1 ) ; indexOfWeight = 0 ; w = epsilon ; //while(w <= (1-epsilon)) while ( indexOfWeight < numberOfWeights ) { weights [ indexOfWeight ] [ 0 ] = w ; weights [ indexOfWeight ] [ 1 ] = 1 - w ; w = w + jump ; indexOfWeight = indexOfWeight + 1 ; } return weights ; }
Generate uniform weight vectors in two dimension
163
8
31,587
public static double [ ] [ ] readFromResourcesInJMetal ( String filePath ) { double [ ] [ ] weights ; Vector < double [ ] > listOfWeights = new Vector <> ( ) ; try { InputStream in = WeightVectors . class . getResourceAsStream ( "/" + filePath ) ; InputStreamReader isr = new InputStreamReader ( in ) ; BufferedReader br = new BufferedReader ( isr ) ; int numberOfObjectives = 0 ; int j ; String aux = br . readLine ( ) ; while ( aux != null ) { StringTokenizer st = new StringTokenizer ( aux ) ; j = 0 ; numberOfObjectives = st . countTokens ( ) ; double [ ] weight = new double [ numberOfObjectives ] ; while ( st . hasMoreTokens ( ) ) { weight [ j ] = new Double ( st . nextToken ( ) ) ; j ++ ; } listOfWeights . add ( weight ) ; aux = br . readLine ( ) ; } br . close ( ) ; weights = new double [ listOfWeights . size ( ) ] [ numberOfObjectives ] ; for ( int indexWeight = 0 ; indexWeight < listOfWeights . size ( ) ; indexWeight ++ ) { System . arraycopy ( listOfWeights . get ( indexWeight ) , 0 , weights [ indexWeight ] , 0 , numberOfObjectives ) ; } } catch ( Exception e ) { throw new JMetalException ( "readFromResourcesInJMetal: failed when reading for file: " + filePath + "" , e ) ; } return weights ; }
Read a set of weight vector from a file in the resources folder in jMetal
346
16
31,588
public static double [ ] [ ] readFromFile ( String filePath ) { double [ ] [ ] weights ; Vector < double [ ] > listOfWeights = new Vector <> ( ) ; try { // Open the file FileInputStream fis = new FileInputStream ( filePath ) ; InputStreamReader isr = new InputStreamReader ( fis ) ; BufferedReader br = new BufferedReader ( isr ) ; int numberOfObjectives = 0 ; int j ; String aux = br . readLine ( ) ; while ( aux != null ) { StringTokenizer st = new StringTokenizer ( aux ) ; j = 0 ; numberOfObjectives = st . countTokens ( ) ; double [ ] weight = new double [ numberOfObjectives ] ; while ( st . hasMoreTokens ( ) ) { weight [ j ] = new Double ( st . nextToken ( ) ) ; j ++ ; } listOfWeights . add ( weight ) ; aux = br . readLine ( ) ; } br . close ( ) ; weights = new double [ listOfWeights . size ( ) ] [ numberOfObjectives ] ; for ( int indexWeight = 0 ; indexWeight < listOfWeights . size ( ) ; indexWeight ++ ) { System . arraycopy ( listOfWeights . get ( indexWeight ) , 0 , weights [ indexWeight ] , 0 , numberOfObjectives ) ; } } catch ( Exception e ) { throw new JMetalException ( "readFromFile: failed when reading for file: " + filePath + "" , e ) ; } return weights ; }
Read a set of weight vector from a file
337
9
31,589
public static double [ ] [ ] invert ( double [ ] [ ] weights , boolean normalize ) { double [ ] [ ] result = new double [ weights . length ] [ weights [ 0 ] . length ] ; for ( int indexOfWeight = 0 ; indexOfWeight < weights . length ; indexOfWeight ++ ) { if ( normalize ) { double sum = 0 ; for ( int indexOfComponent = 0 ; indexOfComponent < weights [ indexOfWeight ] . length ; indexOfComponent ++ ) { sum = sum + ( 1.0 / weights [ indexOfWeight ] [ indexOfComponent ] ) ; } for ( int indexOfComponent = 0 ; indexOfComponent < weights [ indexOfWeight ] . length ; indexOfComponent ++ ) { result [ indexOfWeight ] [ indexOfComponent ] = ( 1.0 / weights [ indexOfWeight ] [ indexOfComponent ] ) / sum ; } } else { for ( int indexOfComponent = 0 ; indexOfComponent < weights [ indexOfWeight ] . length ; indexOfComponent ++ ) result [ indexOfWeight ] [ indexOfComponent ] = 1.0 / weights [ indexOfWeight ] [ indexOfComponent ] ; } } return result ; }
Calculate the inverse of a set of weight vectors
255
11
31,590
protected double evalG ( DoubleSolution solution ) { double g = 0.0 ; for ( int i = 1 ; i < solution . getNumberOfVariables ( ) ; i ++ ) { g += solution . getVariableValue ( i ) ; } double constant = 9.0 / ( solution . getNumberOfVariables ( ) - 1 ) ; return constant * g + 1.0 ; }
Returns the value of the ZDT1 function G .
83
11
31,591
protected double evalH ( double f , double g ) { double h ; h = 1.0 - Math . sqrt ( f / g ) ; return h ; }
Returns the value of the ZDT1 function H .
35
11
31,592
public double generationalDistance ( Front front , Front referenceFront ) { double sum = 0.0 ; for ( int i = 0 ; i < front . getNumberOfPoints ( ) ; i ++ ) { sum += Math . pow ( FrontUtils . distanceToClosestPoint ( front . getPoint ( i ) , referenceFront ) , pow ) ; } sum = Math . pow ( sum , 1.0 / pow ) ; return sum / front . getNumberOfPoints ( ) ; }
Returns the generational distance value for a given front
103
9
31,593
public float linear ( float [ ] x , int m ) { float result = ( float ) 1.0 ; int M = x . length ; for ( int i = 1 ; i <= M - m ; i ++ ) { result *= x [ i - 1 ] ; } if ( m != 1 ) { result *= ( 1 - x [ M - m ] ) ; } return result ; }
Calculate a linear shape
84
6
31,594
public float convex ( float [ ] x , int m ) { float result = ( float ) 1.0 ; int M = x . length ; for ( int i = 1 ; i <= M - m ; i ++ ) { result *= ( 1 - Math . cos ( x [ i - 1 ] * Math . PI * 0.5 ) ) ; } if ( m != 1 ) { result *= ( 1 - Math . sin ( x [ M - m ] * Math . PI * 0.5 ) ) ; } return result ; }
Calculate a convex shape
115
7
31,595
public float mixed ( float [ ] x , int A , float alpha ) { float tmp ; tmp = ( float ) Math . cos ( ( float ) 2.0 * A * ( float ) Math . PI * x [ 0 ] + ( float ) Math . PI * ( float ) 0.5 ) ; tmp /= ( 2.0 * ( float ) A * Math . PI ) ; return ( float ) Math . pow ( ( ( float ) 1.0 - x [ 0 ] - tmp ) , alpha ) ; }
Calculate a mixed shape
110
6
31,596
public float disc ( float [ ] x , int A , float alpha , float beta ) { float tmp ; tmp = ( float ) Math . cos ( ( float ) A * Math . pow ( x [ 0 ] , beta ) * Math . PI ) ; return ( float ) 1.0 - ( float ) Math . pow ( x [ 0 ] , alpha ) * ( float ) Math . pow ( tmp , 2.0 ) ; }
Calculate a disc shape
91
6
31,597
static public double sphere_noise ( double [ ] x ) { double sum = 0.0 ; for ( int i = 0 ; i < x . length ; i ++ ) { sum += x [ i ] * x [ i ] ; } // NOISE // Comment the next line to remove the noise sum *= ( 1.0 + 0.1 * Math . abs ( random . nextGaussian ( ) ) ) ; return ( sum ) ; }
Sphere function with noise
95
4
31,598
static public double schwefel_102 ( double [ ] x ) { double prev_sum , curr_sum , outer_sum ; curr_sum = x [ 0 ] ; outer_sum = ( curr_sum * curr_sum ) ; for ( int i = 1 ; i < x . length ; i ++ ) { prev_sum = curr_sum ; curr_sum = prev_sum + x [ i ] ; outer_sum += ( curr_sum * curr_sum ) ; } return ( outer_sum ) ; }
Schwefel s problem 1 . 2
121
9
31,599
static public double rosenbrock ( double [ ] x ) { double sum = 0.0 ; for ( int i = 0 ; i < ( x . length - 1 ) ; i ++ ) { double temp1 = ( x [ i ] * x [ i ] ) - x [ i + 1 ] ; double temp2 = x [ i ] - 1.0 ; sum += ( 100.0 * temp1 * temp1 ) + ( temp2 * temp2 ) ; } return ( sum ) ; }
Rosenbrock s function
107
6