idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
39,900
|
void setState ( KeyState newState ) { if ( MonocleSettings . settings . traceEvents ) { MonocleTrace . traceEvent ( "Set %s" , newState ) ; } newState . getWindow ( true ) ; state . getKeysPressed ( ) . difference ( keys , newState . getKeysPressed ( ) ) ; if ( ! keys . isEmpty ( ) ) { for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { int key = keys . get ( i ) ; dispatchKeyEvent ( newState , KeyEvent . RELEASE , key ) ; } } keys . clear ( ) ; newState . getKeysPressed ( ) . difference ( keys , state . getKeysPressed ( ) ) ; if ( ! keys . isEmpty ( ) ) { for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { int key = keys . get ( i ) ; if ( key == KeyEvent . VK_CAPS_LOCK ) { capsLock = ! capsLock ; } else if ( key == KeyEvent . VK_NUM_LOCK ) { numLock = ! numLock ; } else if ( key == KeyEvent . VK_C && newState . isControlPressed ( ) ) { AccessController . doPrivileged ( ( PrivilegedAction < Void > ) ( ) -> { if ( "1" . equals ( System . getenv ( "JAVAFX_DEBUG" ) ) ) { System . exit ( 0 ) ; } return null ; } ) ; } dispatchKeyEvent ( newState , KeyEvent . PRESS , key ) ; } } keys . clear ( ) ; newState . copyTo ( state ) ; }
|
Called from the input processor to update the key state and send key events .
|
39,901
|
static void colorKeyCursor ( byte [ ] source , Buffer dest , int targetDepth , int transparentPixel ) { switch ( targetDepth ) { case 32 : colorKeyCursor32 ( source , ( IntBuffer ) dest , transparentPixel ) ; break ; case 16 : colorKeyCursor16 ( source , ( ShortBuffer ) dest , transparentPixel ) ; break ; default : throw new UnsupportedOperationException ( ) ; } }
|
Convert a cursor in 32 - bit BYTE_ARGB_PRE format to a 16 - bit or 32 - bit color - keyed format
|
39,902
|
static void offsetCursor ( Buffer sourceBuffer , Buffer destBuffer , int offsetX , int offsetY , int width , int height , int depth , int transparentPixel ) { switch ( depth ) { case 32 : offsetCursor32 ( ( IntBuffer ) sourceBuffer , ( IntBuffer ) destBuffer , offsetX , offsetY , width , height , transparentPixel ) ; break ; case 16 : offsetCursor16 ( ( ShortBuffer ) sourceBuffer , ( ShortBuffer ) destBuffer , offsetX , offsetY , width , height , transparentPixel ) ; break ; default : throw new UnsupportedOperationException ( ) ; } }
|
Creates a shifted version of the source cursor . Buffers must be ShortBuffers for a bit depth of 16 or IntBuffers for a bit depth of 32 .
|
39,903
|
public void uploadPixels ( Buffer b , int x , int y , int width , int height , float alpha ) { _uploadPixels ( b , x , y , width , height , alpha ) ; }
|
Uploads a pixel buffer to the screen . Called on the JavaFX application thread .
|
39,904
|
protected String resourceName ( final String className ) { String name = className ; if ( ! name . startsWith ( "/" ) ) { name = "/" + name ; } if ( ! name . endsWith ( DOT_GROOVY ) ) { name = name . replace ( '.' , '/' ) ; name += DOT_GROOVY ; } return name ; }
|
Translate class - name into resource - name .
|
39,905
|
private String getVersion ( final ClassLoader classLoader , final String className , final String methodName ) { log . trace ( "Getting version; class-loader: {}, class-name: {}, method-name: {}" , classLoader , className , methodName ) ; try { Class < ? > type = classLoader . loadClass ( className ) ; Method method = type . getMethod ( methodName ) ; Object result = method . invoke ( null ) ; if ( result != null ) { return result . toString ( ) ; } } catch ( Throwable e ) { log . trace ( "Unable determine version from: {}" , className ) ; } return null ; }
|
Get version from Groovy version helper utilities via reflection .
|
39,906
|
public VersionRange before ( final int ... parts ) { checkNotNull ( parts ) ; checkArgument ( parts . length != 0 ) ; StringBuilder buff = new StringBuilder ( ) . append ( "(," ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { buff . append ( parts [ i ] ) ; if ( i + 1 < parts . length ) { buff . append ( "." ) ; } } buff . append ( "-" ) . append ( EARLIEST_SUFFIX ) . append ( ")" ) ; log . trace ( "Range pattern: {}" , buff ) ; return parseRange ( buff . toString ( ) ) ; }
|
Builds a range before version parts .
|
39,907
|
private File resolveBasedir ( ) throws IOException { String path = null ; if ( project != null ) { File file = project . getBasedir ( ) ; if ( file != null ) { path = file . getAbsolutePath ( ) ; } } if ( path == null ) { path = session . getExecutionRootDirectory ( ) ; } if ( path == null ) { path = System . getProperty ( "user.dir" ) ; } return new File ( path ) . getCanonicalFile ( ) ; }
|
Resolves the base directory for the current execution .
|
39,908
|
private void ensureMavenCompatibility ( final ClassLoader classLoader ) throws MojoExecutionException { Version mavenVersion = mavenVersionHelper . detectVersion ( classLoader ) ; if ( mavenVersion == null ) { log . error ( "Unable to determine Maven version" ) ; } else { log . debug ( "Detected Maven version: {}" , mavenVersion ) ; if ( versionHelper . before ( 3 ) . containsVersion ( mavenVersion ) ) { throw new MojoExecutionException ( "Unsupported Maven version: " + mavenVersion ) ; } } }
|
Ensure Maven compatibility . Requires Maven 3 +
|
39,909
|
private void ensureGroovyComparability ( final ClassLoader classLoader ) throws MojoExecutionException { Version groovyVersion = groovyVersionHelper . detectVersion ( classLoader ) ; if ( groovyVersion == null ) { log . error ( "Unable to determine Groovy version" ) ; } else { log . debug ( "Detected Groovy version: {}" , groovyVersion ) ; if ( versionHelper . before ( 2 ) . containsVersion ( groovyVersion ) ) { throw new MojoExecutionException ( "Unsupported Groovy version: " + groovyVersion ) ; } } }
|
Ensure Groovy compatibility . Requires Groovy 2 +
|
39,910
|
private void configureAdditionalClasspath ( final ClassRealm realm ) { log . debug ( "Configuring additional classpath with scope: {}" , classpathScope ) ; List < File > classpath = Lists . newArrayList ( ) ; if ( classpathScope . matches ( compile ) ) { classpath . add ( new File ( project . getBuild ( ) . getOutputDirectory ( ) ) ) ; } if ( classpathScope . matches ( test ) ) { classpath . add ( new File ( project . getBuild ( ) . getTestOutputDirectory ( ) ) ) ; } if ( ! project . getArtifacts ( ) . isEmpty ( ) ) { for ( Artifact artifact : project . getArtifacts ( ) ) { if ( classpathScope . matches ( artifact . getScope ( ) ) ) { File file = artifact . getFile ( ) ; if ( ! file . exists ( ) ) { log . warn ( "Artifact not resolved; ignoring: {}" , artifact ) ; continue ; } classpath . add ( file ) ; } } } if ( ! classpath . isEmpty ( ) ) { log . debug ( "Additional classpath:" ) ; for ( File file : classpath ) { log . debug ( " {}" , file ) ; try { realm . addURL ( file . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw Throwables . propagate ( e ) ; } } } }
|
Configure additional classpath elements for the runtime realm .
|
39,911
|
private Logger createLogger ( ) { String loggerName = String . format ( "%s.%s.Script" , project . getGroupId ( ) , project . getArtifactId ( ) ) ; return LoggerFactory . getLogger ( loggerName ) ; }
|
Create script logger .
|
39,912
|
private Properties createProperties ( ) { propertiesBuilder . setProject ( project ) . setSession ( session ) ; customizeProperties ( propertiesBuilder ) ; Properties props = new Properties ( ) ; props . putAll ( propertiesBuilder . build ( ) ) ; return props ; }
|
Create script execution properties .
|
39,913
|
protected Map < String , Object > createContext ( ) { Map < String , Object > context = Maps . newHashMap ( ) ; context . put ( "log" , createLogger ( ) ) ; context . put ( "container" , containerHelper ) ; context . put ( "plugin" , pluginDescriptor ) ; context . put ( "pluginContext" , getPluginContext ( ) ) ; context . put ( "mojo" , mojoExecution ) ; context . put ( "basedir" , basedir ) ; context . put ( "project" , project ) ; context . put ( "properties" , createProperties ( ) ) ; context . put ( "session" , session ) ; context . put ( "settings" , settings ) ; context . put ( "ant" , MagicContext . ANT_BUILDER ) ; context . put ( "fail" , new FailClosureTarget ( ) ) ; return context ; }
|
Configures the context which will be available to executed scripts as binding variables .
|
39,914
|
public ClassSource create ( final String source ) { checkNotNull ( source ) ; String trimmed = source . trim ( ) ; log . trace ( "Creating class-source from: {}" , trimmed ) ; try { return new ClassSourceImpl ( new URL ( trimmed ) , null , null ) ; } catch ( MalformedURLException e ) { log . trace ( "Not a URL" , e ) ; } try { File file = new File ( trimmed ) . getCanonicalFile ( ) ; if ( file . exists ( ) ) { return new ClassSourceImpl ( null , file , null ) ; } } catch ( IOException e ) { log . trace ( "Not a File" , e ) ; } return new ClassSourceImpl ( null , null , new InlineImpl ( source ) ) ; }
|
Create a class - source from the given source .
|
39,915
|
public synchronized void start ( ) { if ( isStarted ( ) ) { throw new IllegalStateException ( "Failed to start Socket.IO server: server already started" ) ; } log . info ( "Socket.IO server starting" ) ; timer = new HashedWheelTimer ( ) ; timer . start ( ) ; SocketIOHeartbeatScheduler . setHashedWheelTimer ( timer ) ; SocketIOHeartbeatScheduler . setHeartbeatInterval ( configuration . getHeartbeatInterval ( ) ) ; SocketIOHeartbeatScheduler . setHeartbeatTimeout ( configuration . getHeartbeatTimeout ( ) ) ; ServerBootstrapFactory bootstrapFactory = serverBootstrapFactory != null ? serverBootstrapFactory : new DefaultServerBootstrapFactory ( configuration ) ; bootstrap = bootstrapFactory . createServerBootstrap ( ) ; bootstrap . childHandler ( new SocketIOChannelInitializer ( configuration , listener , pipelineModifier ) ) ; bootstrap . bind ( configuration . getPort ( ) ) . syncUninterruptibly ( ) ; state = State . STARTED ; log . info ( "Socket.IO server started: {}" , configuration ) ; }
|
Starts Socket . IO server with current configuration settings .
|
39,916
|
public synchronized void stop ( ) { if ( isStopped ( ) ) { throw new IllegalStateException ( "Failed to stop Socket.IO server: server already stopped" ) ; } log . info ( "Socket.IO server stopping" ) ; timer . stop ( ) ; bootstrap . config ( ) . group ( ) . shutdownGracefully ( ) . syncUninterruptibly ( ) ; state = State . STOPPED ; log . info ( "Socket.IO server stopped" ) ; }
|
Stops Socket . IO server .
|
39,917
|
private void sendError ( ChannelHandlerContext ctx , HttpResponseStatus status ) { HttpResponse response = new DefaultHttpResponse ( HttpVersion . HTTP_1_1 , status ) ; response . headers ( ) . set ( HttpHeaderNames . CONTENT_TYPE , "text/plain; charset=UTF-8" ) ; ByteBuf content = Unpooled . copiedBuffer ( "Failure: " + status . toString ( ) + "\r\n" , CharsetUtil . UTF_8 ) ; ctx . write ( response ) ; ctx . writeAndFlush ( content ) . addListener ( ChannelFutureListener . CLOSE ) ; }
|
Sends an Error response with status message
|
39,918
|
public static void main ( String [ ] args ) throws Exception { if ( args . length != 1 ) { System . err . println ( "usage: generator <basedir>" ) ; System . exit ( - 1 ) ; } File baseDir = new File ( args [ 0 ] ) ; System . out . println ( "Using baseDir: " + baseDir . getAbsolutePath ( ) ) ; new ProjectGenerator ( baseDir ) . generate ( ) ; }
|
Main point of entry from the command line . Pass the base directory for generation as the only argument .
|
39,919
|
public Plan repeatEvery ( final Integer repeatEvery , final PlanRepeatUnit unit ) { this . repeatEvery = repeatEvery ; this . repeatUnit = unit == null ? null : unit . name ( ) . toLowerCase ( ) ; return this ; }
|
The duration of each cycle . Required .
|
39,920
|
public Charge createCharge ( RequestBuilder request ) throws OpenpayServiceException , ServiceUnavailableException { String path = String . format ( FOR_MERCHANT_PATH , this . getMerchantId ( ) ) ; return this . getJsonClient ( ) . post ( path , request . asMap ( ) , Charge . class ) ; }
|
Creates any kind of charge at the Merchant level .
|
39,921
|
public Charge confirmCapture ( final ConfirmCaptureParams params ) throws OpenpayServiceException , ServiceUnavailableException { String path = String . format ( CAPTURE_FOR_MERCHANT_PATH , this . getMerchantId ( ) , params . getChargeId ( ) ) ; return this . getJsonClient ( ) . post ( path , params . asMap ( ) , Charge . class ) ; }
|
Confirms a charge that was made with the option capture set to false .
|
39,922
|
public Charge confirmCharge ( final ConfirmChargeParams params ) throws OpenpayServiceException , ServiceUnavailableException { String path = String . format ( CONFIRM_FOR_MERCHANT_PATH , this . getMerchantId ( ) , params . getChargeId ( ) ) ; return this . getJsonClient ( ) . post ( path , params . asMap ( ) , Charge . class ) ; }
|
Confirms a charge that was made with the option confirm set to false .
|
39,923
|
public Charge create ( final String customerId , final CreateStoreChargeParams request ) throws OpenpayServiceException , ServiceUnavailableException { return createCharge ( customerId , request ) ; }
|
Creates a store charge at the Customer level .
|
39,924
|
public OpenpayFeesSummary getSummary ( final int year , final int month ) throws OpenpayServiceException , ServiceUnavailableException { String path = String . format ( FEES_PATH , this . getMerchantId ( ) ) ; Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( "year" , String . valueOf ( year ) ) ; params . put ( "month" , String . valueOf ( month ) ) ; return this . getJsonClient ( ) . get ( path , params , OpenpayFeesSummary . class ) ; }
|
Retrieve the summary of the charged fees in the given month . The amounts retrieved in the current month may change on a daily basis .
|
39,925
|
public List < GenericTransaction > getDetails ( final int year , final int month , final FeeDetailsType feeType , final PaginationParams pagination ) throws OpenpayServiceException , ServiceUnavailableException { String path = String . format ( FEES_DETAILS_PATH , this . getMerchantId ( ) ) ; Map < String , String > params = new HashMap < String , String > ( ) ; if ( pagination != null ) { params . putAll ( pagination . asMap ( ) ) ; } params . put ( "year" , String . valueOf ( year ) ) ; params . put ( "month" , String . valueOf ( month ) ) ; params . put ( "fee_type" , feeType . name ( ) . toLowerCase ( ) ) ; return this . getJsonClient ( ) . list ( path , params , GenericTransaction . class ) ; }
|
Retrieves the list of transactions that affected the charged or refunded fees on a given month . Transactions in the CHARGED or REFUNDED type of detail add their fee to the total while the ones in CHARGED_ADJUSTMENTS and REFUNDED_ADJUSTMENTS add their amount .
|
39,926
|
@ SuppressWarnings ( "unchecked" ) public < T extends RequestBuilder > T with ( final String jsonParam , final Object obj ) { this . parameters . put ( jsonParam , obj ) ; return ( T ) this ; }
|
Adds the given parameter to the map and returns this same object .
|
39,927
|
public Webhook addEventTypes ( final String eventType ) { if ( this . eventTypes == null ) { this . eventTypes = new ArrayList < String > ( ) ; } this . eventTypes . add ( eventType ) ; return this ; }
|
Webhook eventType . Required .
|
39,928
|
public TransactionsPayoutResume getResume ( final String payoutId ) throws OpenpayServiceException , ServiceUnavailableException { String path = String . format ( PAYOUT_TRANSACTIONS_PATH , this . getMerchantId ( ) , payoutId ) ; return this . getJsonClient ( ) . get ( path , TransactionsPayoutResume . class ) ; }
|
Retrieve the resume of the transactions of the given payoutid .
|
39,929
|
public List < GenericTransaction > getDetails ( final String payoutId , final TransactionsPayoutType transactionsPayoutType , final PaginationParams pagination ) throws OpenpayServiceException , ServiceUnavailableException { String path = String . format ( PAYOUT_TRANSACTIONS_DETAILS_PATH , this . getMerchantId ( ) , payoutId ) ; Map < String , String > params = new HashMap < String , String > ( ) ; if ( pagination != null ) { params . putAll ( pagination . asMap ( ) ) ; } params . put ( "detail_type" , transactionsPayoutType . name ( ) . toLowerCase ( ) ) ; return this . getJsonClient ( ) . list ( path , params , GenericTransaction . class ) ; }
|
Retrieves the list of transactions that affected the payout . . Transactions in the IN or OUT type of detail add their fee to the total while the ones in CHARGED_ADJUSTMENTS and REFUNDED_ADJUSTMENTS add their amount .
|
39,930
|
public void configure ( String parameters ) { if ( parameters . isEmpty ( ) ) { return ; } List < String > values = Op . split ( parameters , " " , true ) ; final int required = 2 ; if ( values . size ( ) < required ) { throw new RuntimeException ( MessageFormat . format ( "[configuration error] activation {0} requires {1} parameters" , this . getClass ( ) . getSimpleName ( ) , required ) ) ; } setNumberOfRules ( Integer . parseInt ( values . get ( 0 ) ) ) ; setThreshold ( Op . toDouble ( values . get ( 1 ) ) ) ; }
|
Configures the activation method with the given number of rules and threshold
|
39,931
|
public static Linear create ( String name , Engine engine , double ... coefficients ) { List < Double > coefficientsList = new ArrayList < Double > ( coefficients . length ) ; for ( double coefficient : coefficients ) { coefficientsList . add ( coefficient ) ; } return new Linear ( name , coefficientsList , engine ) ; }
|
Creates a Linear term from a variadic set of coefficients . The number of variadic arguments should be the same as the number of input variables in the engine plus one in order to match the size of the list
|
39,932
|
public T getObject ( String key ) { if ( this . objects . containsKey ( key ) ) { return this . objects . get ( key ) ; } return null ; }
|
Gets the object registered by the given key not a clone of the object
|
39,933
|
@ SuppressWarnings ( "unchecked" ) public T cloneObject ( String key ) { if ( this . objects . containsKey ( key ) ) { T object = this . objects . get ( key ) ; if ( object != null ) { try { return ( T ) object . clone ( ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } return null ; } throw new RuntimeException ( "[cloning error] object by name <" + key + "> not registered in " + getClass ( ) . getSimpleName ( ) ) ; }
|
Creates a cloned object by executing the clone method on the registered object
|
39,934
|
public void configure ( String conjunction , String disjunction , String implication , String aggregation , String defuzzifier , String activation ) { TNormFactory tnormFactory = FactoryManager . instance ( ) . tnorm ( ) ; SNormFactory snormFactory = FactoryManager . instance ( ) . snorm ( ) ; TNorm conjunctionObject = tnormFactory . constructObject ( conjunction ) ; SNorm disjunctionObject = snormFactory . constructObject ( disjunction ) ; TNorm implicationObject = tnormFactory . constructObject ( implication ) ; SNorm aggregationObject = snormFactory . constructObject ( aggregation ) ; Defuzzifier defuzzifierObject = FactoryManager . instance ( ) . defuzzifier ( ) . constructObject ( defuzzifier ) ; Activation activationObject = FactoryManager . instance ( ) . activation ( ) . constructObject ( activation ) ; configure ( conjunctionObject , disjunctionObject , implicationObject , aggregationObject , defuzzifierObject , activationObject ) ; }
|
Configures the engine with the given operators
|
39,935
|
public void configure ( TNorm conjunction , SNorm disjunction , TNorm implication , SNorm aggregation , Defuzzifier defuzzifier , Activation activation ) { try { for ( RuleBlock ruleblock : this . ruleBlocks ) { ruleblock . setConjunction ( conjunction == null ? null : conjunction . clone ( ) ) ; ruleblock . setDisjunction ( disjunction == null ? null : disjunction . clone ( ) ) ; ruleblock . setImplication ( implication == null ? null : implication . clone ( ) ) ; ruleblock . setActivation ( activation == null ? new General ( ) : activation . clone ( ) ) ; } for ( OutputVariable outputVariable : this . outputVariables ) { outputVariable . setDefuzzifier ( defuzzifier == null ? null : defuzzifier . clone ( ) ) ; outputVariable . setAggregation ( aggregation == null ? null : aggregation . clone ( ) ) ; } } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } }
|
Configures the engine with clones of the given operators .
|
39,936
|
public List < Variable > variables ( ) { List < Variable > result = new ArrayList < Variable > ( inputVariables . size ( ) + outputVariables . size ( ) ) ; result . addAll ( inputVariables ) ; result . addAll ( outputVariables ) ; return result ; }
|
Returns a list that contains the input variables followed by the output variables in the order of insertion
|
39,937
|
public InputVariable removeInputVariable ( String name ) { for ( Iterator < InputVariable > it = this . inputVariables . iterator ( ) ; it . hasNext ( ) ; ) { InputVariable inputVariable = it . next ( ) ; if ( inputVariable . getName ( ) . equals ( name ) ) { it . remove ( ) ; return inputVariable ; } } throw new RuntimeException ( String . format ( "[engine error] no input variable by name <%s>" , name ) ) ; }
|
Removes the given input variable from the list of input variables .
|
39,938
|
public boolean hasInputVariable ( String name ) { for ( InputVariable inputVariable : this . inputVariables ) { if ( inputVariable . getName ( ) . equals ( name ) ) { return true ; } } return false ; }
|
Indicates whether an input variable of the given name is in the input variables
|
39,939
|
public OutputVariable removeOutputVariable ( String name ) { for ( Iterator < OutputVariable > it = this . outputVariables . iterator ( ) ; it . hasNext ( ) ; ) { OutputVariable outputVariable = it . next ( ) ; if ( outputVariable . getName ( ) . equals ( name ) ) { it . remove ( ) ; return outputVariable ; } } throw new RuntimeException ( String . format ( "[engine error] no output variable by name <%s>" , name ) ) ; }
|
Removes the output variable of the given name .
|
39,940
|
public boolean hasOutputVariable ( String name ) { for ( OutputVariable outputVariable : this . outputVariables ) { if ( outputVariable . getName ( ) . equals ( name ) ) { return true ; } } return false ; }
|
Indicates whether an output variable of the given name is in the output variables
|
39,941
|
public double compute ( double a , double b ) { if ( Op . isEq ( Op . min ( a , b ) , 0.0 ) ) { return Op . max ( a , b ) ; } return 1.0 ; }
|
Computes the drastic sum of two membership function values
|
39,942
|
public void register ( String simpleName , Class < ? extends T > clazz ) { this . constructors . put ( simpleName , clazz ) ; }
|
Registers the class in the factory utilizing the given key
|
39,943
|
public T constructObject ( String simpleName ) { if ( simpleName == null ) { return null ; } if ( this . constructors . containsKey ( simpleName ) ) { try { Class < ? extends T > clazz = this . constructors . get ( simpleName ) ; if ( clazz != null ) { return clazz . newInstance ( ) ; } return null ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } throw new RuntimeException ( "[construction error] constructor <" + simpleName + "> not registered in " + getClass ( ) . getSimpleName ( ) ) ; }
|
Creates an object by instantiating the registered class associated to the given key
|
39,944
|
public double compute ( double a , double b ) { if ( Op . isGt ( a + b , 1.0 ) ) { return Op . min ( a , b ) ; } return 0.0 ; }
|
Computes the nilpotent minimum of two membership function values
|
39,945
|
public Set < String > availableOperators ( ) { Set < String > operators = new HashSet < String > ( this . getObjects ( ) . keySet ( ) ) ; Iterator < String > it = operators . iterator ( ) ; while ( it . hasNext ( ) ) { String key = it . next ( ) ; if ( ! getObject ( key ) . isOperator ( ) ) { it . remove ( ) ; } } return operators ; }
|
Returns a set of the operators available
|
39,946
|
public Set < String > availableFunctions ( ) { Set < String > functions = new HashSet < String > ( this . getObjects ( ) . keySet ( ) ) ; Iterator < String > it = functions . iterator ( ) ; while ( it . hasNext ( ) ) { String key = it . next ( ) ; if ( ! getObject ( key ) . isFunction ( ) ) { it . remove ( ) ; } } return functions ; }
|
Returns a set of the functions available
|
39,947
|
public static double min ( double a , double b ) { if ( Double . isNaN ( a ) ) { return b ; } if ( Double . isNaN ( b ) ) { return a ; } return a < b ? a : b ; }
|
Returns the minimum between the two parameters
|
39,948
|
public static boolean in ( double x , double min , double max ) { return in ( x , min , max , true , true ) ; }
|
Indicates whether x is within the closed boundaries
|
39,949
|
public static boolean isEq ( double a , double b ) { return a == b || Math . abs ( a - b ) < FuzzyLite . macheps || ( Double . isNaN ( a ) && Double . isNaN ( b ) ) ; }
|
Returns whether a is equal to b at the default tolerance
|
39,950
|
public static double variance ( double [ ] x , double mean ) { if ( x . length == 0 ) { return Double . NaN ; } if ( x . length == 1 ) { return 0.0 ; } double result = 0.0 ; for ( double i : x ) { result += ( i - mean ) * ( i - mean ) ; } result /= - 1 + x . length ; return result ; }
|
Computes the variance of the vector using the given mean
|
39,951
|
public static double standardDeviation ( double [ ] x , double mean ) { if ( x . length == 0 ) { return Double . NaN ; } if ( x . length == 1 ) { return 0.0 ; } return Math . sqrt ( variance ( x , mean ) ) ; }
|
Computes the standard deviation of the vector using the given mean
|
39,952
|
public static List < String > split ( String string , String delimiter ) { return split ( string , delimiter , true ) ; }
|
Splits the string around the given delimiter ignoring empty splits
|
39,953
|
public static List < String > split ( String string , String delimiter , boolean ignoreEmpty ) { List < String > result = new ArrayList < String > ( ) ; if ( string . isEmpty ( ) || delimiter . isEmpty ( ) ) { result . add ( string ) ; return result ; } int position = 0 , next = 0 ; while ( next >= 0 ) { next = string . indexOf ( delimiter , position ) ; String token ; if ( next < 0 ) { token = string . substring ( position ) ; } else { token = string . substring ( position , next ) ; } if ( ! ( token . isEmpty ( ) && ignoreEmpty ) ) { result . add ( token ) ; } if ( next >= 0 ) { position = next + delimiter . length ( ) ; } } return result ; }
|
Splits the string around the given delimiter
|
39,954
|
public static double toDouble ( String x ) throws NumberFormatException { if ( "nan" . equals ( x ) ) { return Double . NaN ; } if ( "inf" . equals ( x ) ) { return Double . POSITIVE_INFINITY ; } if ( "-inf" . equals ( x ) ) { return Double . NEGATIVE_INFINITY ; } return Double . parseDouble ( x ) ; }
|
Parses the given string into a scalar value
|
39,955
|
public static double [ ] toDoubles ( String x , double alternative ) throws NumberFormatException { String [ ] tokens = x . split ( "\\s+" ) ; double [ ] result = new double [ tokens . length ] ; for ( int i = 0 ; i < tokens . length ; ++ i ) { result [ i ] = Op . toDouble ( tokens [ i ] , alternative ) ; } return result ; }
|
Parses the given string into a vector of scalar values
|
39,956
|
public static boolean increment ( int [ ] array , int position , int [ ] min , int [ ] max ) { if ( array . length == 0 || position < 0 ) { return false ; } boolean incremented = true ; if ( array [ position ] < max [ position ] ) { ++ array [ position ] ; } else { incremented = ! ( position == 0 ) ; array [ position ] = min [ position ] ; -- position ; if ( position >= 0 ) { incremented = increment ( array , position , min , max ) ; } } return incremented ; }
|
Increments x by the unit at the given position treating the entire vector as a number . For example incrementing
|
39,957
|
public static String validName ( String name ) { if ( name == null || name . trim ( ) . isEmpty ( ) ) { return "unnamed" ; } StringBuilder result = new StringBuilder ( ) ; for ( char c : name . toCharArray ( ) ) { if ( c == '_' || c == '.' || Character . isLetterOrDigit ( c ) ) { result . append ( c ) ; } } return result . toString ( ) ; }
|
Returns a valid name for variables
|
39,958
|
public static Discrete create ( String name , double ... xy ) { final int mod2 = xy . length % 2 ; List < Pair > xyValues = new ArrayList < Pair > ( xy . length / 2 ) ; for ( int i = 0 ; i < xy . length - mod2 ; i += 2 ) { xyValues . add ( new Pair ( xy [ i ] , xy [ i + 1 ] ) ) ; } Discrete result = new Discrete ( name , xyValues ) ; if ( mod2 != 0 ) { result . setHeight ( xy [ xy . length - 1 ] ) ; } return new Discrete ( name , xyValues ) ; }
|
Creates a Discrete term from a variadic set of values .
|
39,959
|
public static Discrete discretize ( Term term , double start , double end , int resolution , boolean boundedMembershipFunction ) { Discrete result = new Discrete ( term . getName ( ) ) ; double dx = ( end - start ) / resolution ; double x , y ; for ( int i = 0 ; i <= resolution ; ++ i ) { x = start + i * dx ; y = term . membership ( x ) ; if ( boundedMembershipFunction ) { y = Op . bound ( y , 0.0 , 1.0 ) ; } result . add ( new Discrete . Pair ( x , y ) ) ; } return result ; }
|
Discretizes the given term
|
39,960
|
public double membership ( double x ) { if ( Double . isNaN ( x ) ) { return Double . NaN ; } if ( xy . isEmpty ( ) ) { throw new RuntimeException ( "[discrete error] term is empty" ) ; } Pair first = xy . get ( 0 ) ; Pair last = xy . get ( xy . size ( ) - 1 ) ; if ( Op . isLE ( x , first . getX ( ) ) ) { return height * first . getY ( ) ; } if ( Op . isGE ( x , last . getX ( ) ) ) { return height * last . getY ( ) ; } Discrete . Pair value = new Discrete . Pair ( x , Double . NaN ) ; int upper = Collections . binarySearch ( xy , value , ASCENDANTLY ) ; if ( upper >= 0 ) { return height * xy . get ( upper ) . y ; } upper = Math . abs ( upper + 1 ) ; int lower = upper - 1 ; return height * Op . scale ( x , xy . get ( lower ) . getX ( ) , xy . get ( upper ) . getX ( ) , xy . get ( lower ) . getY ( ) , xy . get ( upper ) . getY ( ) ) ; }
|
Computes the membership function evaluated at x by using binary search to find the lower and upper bounds of x and then linearly interpolating the membership function between the bounds .
|
39,961
|
public List < Double > x ( ) { List < Double > result = new ArrayList < Double > ( xy . size ( ) ) ; for ( Discrete . Pair pair : xy ) { result . add ( pair . x ) ; } return result ; }
|
Creates fills and returns a list containing the x values
|
39,962
|
public static List < Double > toList ( List < Pair > xyValues ) { List < Double > result = new ArrayList < Double > ( xyValues . size ( ) * 2 ) ; for ( Pair pair : xyValues ) { result . add ( pair . getX ( ) ) ; result . add ( pair . getY ( ) ) ; } return result ; }
|
Creates a list of scalars from a list of Pair given in the form
|
39,963
|
public static String formatXY ( List < Discrete . Pair > xy , String prefix , String innerSeparator , String suffix , String outerSeparator ) { StringBuilder result = new StringBuilder ( ) ; Iterator < Pair > it = xy . iterator ( ) ; while ( it . hasNext ( ) ) { Pair pair = it . next ( ) ; result . append ( prefix ) . append ( Op . str ( pair . getX ( ) ) ) . append ( innerSeparator ) . append ( Op . str ( pair . getY ( ) ) ) . append ( suffix ) ; if ( it . hasNext ( ) ) { result . append ( outerSeparator ) ; } } return result . toString ( ) ; }
|
Formats a vector of Pair into a string in the form
|
39,964
|
public void configure ( String parameters ) { if ( parameters . isEmpty ( ) ) { return ; } List < String > values = Op . split ( parameters , " " , true ) ; final int required = 2 ; if ( values . size ( ) < required ) { throw new RuntimeException ( MessageFormat . format ( "[configuration error] activation {0} requires {1} parameters" , this . getClass ( ) . getSimpleName ( ) , required ) ) ; } setComparison ( Comparison . fromOperator ( values . get ( 0 ) ) ) ; setValue ( Op . toDouble ( values . get ( 1 ) ) ) ; }
|
Configures the activation method with the comparison operator and the threshold .
|
39,965
|
boolean activatesWith ( double activationDegree ) { if ( Comparison . LessThan == this . comparison ) { return Op . isLt ( activationDegree , getValue ( ) ) ; } if ( Comparison . LessThanOrEqualTo == this . comparison ) { return Op . isLE ( activationDegree , getValue ( ) ) ; } if ( Comparison . EqualTo == this . comparison ) { return Op . isEq ( activationDegree , getValue ( ) ) ; } if ( Comparison . NotEqualTo == this . comparison ) { return ! Op . isEq ( activationDegree , getValue ( ) ) ; } if ( Comparison . GreaterThanOrEqualTo == this . comparison ) { return Op . isGE ( activationDegree , getValue ( ) ) ; } if ( Comparison . GreaterThan == this . comparison ) { return Op . isGt ( activationDegree , getValue ( ) ) ; } return false ; }
|
Returns whether the activation method will activate a rule with the given activation degree
|
39,966
|
public double compute ( double a , double b ) { return ( a * b ) / ( 2 - ( a + b - a * b ) ) ; }
|
Computes the Einstein product of two membership function values
|
39,967
|
public void toFile ( File file , Engine engine , InputVariable a , InputVariable b , int values , FldExporter . ScopeOfValues scope , List < OutputVariable > outputVariables ) throws IOException { BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( file ) , FuzzyLite . UTF_8 ) ) ; try { writeScriptExportingDataFrame ( engine , writer , a , b , values , scope , outputVariables ) ; } catch ( RuntimeException ex ) { throw ex ; } catch ( IOException ex ) { throw ex ; } finally { writer . close ( ) ; } }
|
Creates an R script file plotting multiple surfaces based on a data frame generated with the given number of values and scope for the two input variables
|
39,968
|
public void toFile ( File file , Engine engine , InputVariable a , InputVariable b , Reader reader , List < OutputVariable > outputVariables ) throws IOException { BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( file ) , FuzzyLite . UTF_8 ) ) ; try { writeScriptExportingDataFrame ( engine , writer , a , b , reader , outputVariables ) ; } catch ( RuntimeException ex ) { throw ex ; } catch ( IOException ex ) { throw ex ; } finally { writer . close ( ) ; } }
|
Creates an R script file plotting multiple surfaces based on the input stream of values for the two input variables .
|
39,969
|
public void writeScriptImportingDataFrame ( Engine engine , Writer writer , InputVariable a , InputVariable b , String dataFramePath , List < OutputVariable > outputVariables ) throws IOException { writeScriptHeader ( writer , engine ) ; writer . append ( "engine.fldFile = \"" + dataFramePath + "\"\n" ) ; writer . append ( "if (require(data.table)) {\n" + " engine.df = data.table::fread(engine.fldFile, sep=\"auto\", header=\"auto\")\n" + "} else {\n" + " engine.df = read.table(engine.fldFile, header=TRUE)\n" + "}\n" ) ; writer . append ( "\n" ) ; writeScriptPlots ( writer , a , b , outputVariables ) ; }
|
Writes an R script plotting multiple surfaces based on a manually imported data frame containing the data for the two input variables on the output variables .
|
39,970
|
public double evaluate ( Map < String , Double > localVariables ) { if ( this . root == null ) { throw new RuntimeException ( "[function error] evaluation failed " + "because function is not loaded" ) ; } return this . root . evaluate ( localVariables ) ; }
|
Computes the function value of this term using the given map of variable substitutions .
|
39,971
|
public static Function create ( String name , String formula , Engine engine ) { Function result = new Function ( name ) ; try { result . load ( formula , engine ) ; } catch ( RuntimeException ex ) { throw ex ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } return result ; }
|
Creates a Function term with the given parameters
|
39,972
|
public void load ( String formula , Engine engine ) { this . root = parse ( formula ) ; this . formula = formula ; this . engine = engine ; }
|
Loads the given formula expressed in infix notation and sets the engine holding the variables to which the formula refers .
|
39,973
|
public Node parse ( String text ) { if ( text . isEmpty ( ) ) { return null ; } String postfix = toPostfix ( text ) ; Deque < Node > stack = new ArrayDeque < Node > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( postfix ) ; String token ; FunctionFactory factory = FactoryManager . instance ( ) . function ( ) ; while ( tokenizer . hasMoreTokens ( ) ) { token = tokenizer . nextToken ( ) ; Element element = factory . getObject ( token ) ; boolean isOperand = element == null && ! "(" . equals ( token ) && ! ")" . equals ( token ) && ! "," . equals ( token ) ; if ( element != null ) { if ( element . getArity ( ) > stack . size ( ) ) { throw new RuntimeException ( String . format ( "[function error] " + "operator <%s> has arity <%d>, " + "but <%d> elements are available: (%s)" , element . getName ( ) , element . getArity ( ) , stack . size ( ) , Op . join ( stack , ", " ) ) ) ; } Node node ; try { node = new Node ( element . clone ( ) ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } node . left = stack . pop ( ) ; if ( element . getArity ( ) == 2 ) { node . right = stack . pop ( ) ; } stack . push ( node ) ; } else if ( isOperand ) { Node node ; try { double value = Op . toDouble ( token ) ; node = new Node ( value ) ; } catch ( Exception ex ) { node = new Node ( token ) ; } stack . push ( node ) ; } } if ( stack . size ( ) != 1 ) { throw new RuntimeException ( String . format ( "[function error] ill-formed formula <%s> due to: <%s>" , text , Op . join ( stack , ";" ) ) ) ; } return stack . pop ( ) ; }
|
Creates a node representing a binary expression tree from the given formula
|
39,974
|
public double membership ( double x ) { if ( Double . isNaN ( x ) ) { return Double . NaN ; } double mu = 0.0 ; for ( Activated term : this . terms ) { mu = this . aggregation . compute ( mu , term . membership ( x ) ) ; } return mu ; }
|
Aggregates the membership function values of x utilizing the aggregation operator
|
39,975
|
public Activated highestActivatedTerm ( ) { Activated maximumTerm = null ; double maximumActivation = Double . POSITIVE_INFINITY ; for ( Activated activated : terms ) { if ( Op . isGt ( activated . getDegree ( ) , maximumActivation ) ) { maximumActivation = activated . getDegree ( ) ; maximumTerm = activated ; } } return maximumTerm ; }
|
Iterates over the Activated terms to find the term with the maximum activation degree
|
39,976
|
public double activateWith ( TNorm conjunction , SNorm disjunction ) { if ( ! isLoaded ( ) ) { throw new RuntimeException ( String . format ( "[rule error] the following rule is not loaded: %s" , text ) ) ; } activationDegree = weight * antecedent . activationDegree ( conjunction , disjunction ) ; return activationDegree ; }
|
Activates the rule by computing its activation degree using the given conjunction and disjunction operators
|
39,977
|
public void unload ( ) { deactivate ( ) ; if ( getAntecedent ( ) != null ) { getAntecedent ( ) . unload ( ) ; } if ( getConsequent ( ) != null ) { getConsequent ( ) . unload ( ) ; } }
|
Unloads the rule
|
39,978
|
public void load ( String rule , Engine engine ) { deactivate ( ) ; setEnabled ( true ) ; setText ( rule ) ; StringTokenizer tokenizer = new StringTokenizer ( rule ) ; String token ; StringBuilder strAntecedent = new StringBuilder ( ) ; StringBuilder strConsequent = new StringBuilder ( ) ; double ruleWeight = 1.0 ; final byte S_NONE = 0 , S_IF = 1 , S_THEN = 2 , S_WITH = 3 , S_END = 4 ; byte state = S_NONE ; try { while ( tokenizer . hasMoreTokens ( ) ) { token = tokenizer . nextToken ( ) ; int commentIndex = token . indexOf ( '#' ) ; if ( commentIndex >= 0 ) { token = token . substring ( 0 , commentIndex ) ; } switch ( state ) { case S_NONE : if ( Rule . FL_IF . equals ( token ) ) { state = S_IF ; } else { throw new RuntimeException ( String . format ( "[syntax error] expected keyword <%s>, but found <%s> in rule: %s" , Rule . FL_IF , token , rule ) ) ; } break ; case S_IF : if ( Rule . FL_THEN . equals ( token ) ) { state = S_THEN ; } else { strAntecedent . append ( token ) . append ( " " ) ; } break ; case S_THEN : if ( Rule . FL_WITH . equals ( token ) ) { state = S_WITH ; } else { strConsequent . append ( token ) . append ( " " ) ; } break ; case S_WITH : try { ruleWeight = Op . toDouble ( token ) ; state = S_END ; } catch ( NumberFormatException ex ) { throw ex ; } break ; case S_END : throw new RuntimeException ( String . format ( "[syntax error] unexpected token <%s> at the end of rule" , token ) ) ; default : throw new RuntimeException ( String . format ( "[syntax error] unexpected state <%s>" , state ) ) ; } } if ( state == S_NONE ) { throw new RuntimeException ( String . format ( "[syntax error] %s rule: %s" , ( rule . isEmpty ( ) ? "empty" : "ignored" ) , rule ) ) ; } else if ( state == S_IF ) { throw new RuntimeException ( String . format ( "[syntax error] keyword <%s> not found in rule: %s" , Rule . FL_THEN , rule ) ) ; } else if ( state == S_WITH ) { throw new RuntimeException ( String . format ( "[syntax error] expected a numeric value as the weight of the rule: %s" , rule ) ) ; } getAntecedent ( ) . load ( strAntecedent . toString ( ) , engine ) ; getConsequent ( ) . load ( strConsequent . toString ( ) , engine ) ; setWeight ( ruleWeight ) ; } catch ( RuntimeException ex ) { unload ( ) ; throw ex ; } }
|
Loads the rule with the given text and uses the engine to identify and retrieve references to the input variables and output variables as required
|
39,979
|
public static Rule parse ( String rule , Engine engine ) { Rule result = new Rule ( ) ; result . load ( rule , engine ) ; return result ; }
|
Parses and creates a new rule based on the text passed
|
39,980
|
public double compute ( double a , double b ) { if ( Op . isLt ( a + b , 1.0 ) ) { return Op . max ( a , b ) ; } return 1.0 ; }
|
Computes the nilpotent maximum of two membership function values
|
39,981
|
public Direction direction ( ) { double range = this . end - this . start ; if ( ! Op . isFinite ( range ) || Op . isEq ( range , 0.0 ) ) { return Direction . Zero ; } if ( Op . isGt ( range , 0.0 ) ) { return Direction . Positive ; } return Direction . Negative ; }
|
Returns the direction of the ramp
|
39,982
|
public void activate ( RuleBlock ruleBlock ) { if ( FuzzyLite . isDebugging ( ) ) { FuzzyLite . logger ( ) . log ( Level . FINE , "Activation: {0} {1}" , new String [ ] { getClass ( ) . getName ( ) , parameters ( ) } ) ; } TNorm conjunction = ruleBlock . getConjunction ( ) ; SNorm disjunction = ruleBlock . getDisjunction ( ) ; TNorm implication = ruleBlock . getImplication ( ) ; PriorityQueue < Rule > rulesToActivate = new PriorityQueue < Rule > ( numberOfRules , new Ascending ( ) ) ; for ( Rule rule : ruleBlock . getRules ( ) ) { rule . deactivate ( ) ; if ( rule . isLoaded ( ) ) { double activationDegree = rule . activateWith ( conjunction , disjunction ) ; if ( Op . isGt ( activationDegree , 0.0 ) ) { rulesToActivate . offer ( rule ) ; } } } int activated = 0 ; while ( ! rulesToActivate . isEmpty ( ) && activated ++ < numberOfRules ) { rulesToActivate . poll ( ) . trigger ( implication ) ; } }
|
Activates the rules with the lowest activation degrees in the given rule block
|
39,983
|
public void activate ( RuleBlock ruleBlock ) { if ( FuzzyLite . isDebugging ( ) ) { FuzzyLite . logger ( ) . log ( Level . FINE , "Activation: {0} {1}" , new String [ ] { getClass ( ) . getName ( ) , parameters ( ) } ) ; } TNorm conjunction = ruleBlock . getConjunction ( ) ; SNorm disjunction = ruleBlock . getDisjunction ( ) ; TNorm implication = ruleBlock . getImplication ( ) ; double sumActivationDegrees = 0.0 ; List < Rule > rulesToActivate = new ArrayList < Rule > ( ruleBlock . getRules ( ) . size ( ) ) ; for ( Rule rule : ruleBlock . getRules ( ) ) { rule . deactivate ( ) ; if ( rule . isLoaded ( ) ) { double activationDegree = rule . activateWith ( conjunction , disjunction ) ; rulesToActivate . add ( rule ) ; sumActivationDegrees += activationDegree ; } } for ( Rule rule : rulesToActivate ) { double activationDegree = rule . getActivationDegree ( ) / sumActivationDegrees ; rule . setActivationDegree ( activationDegree ) ; rule . trigger ( implication ) ; } }
|
Activates the rules utilizing activation degrees proportional to the activation degrees of the other rules in the rule block .
|
39,984
|
public void prepare ( int values , FldExporter . ScopeOfValues scope ) { if ( engine == null ) { throw new RuntimeException ( "[benchmark error] engine not set before " + "preparing for values and scope" ) ; } int resolution ; if ( scope == FldExporter . ScopeOfValues . AllVariables ) { resolution = - 1 + ( int ) Math . max ( 1.0 , Math . pow ( values , 1.0 / engine . numberOfInputVariables ( ) ) ) ; } else { resolution = values - 1 ; } int [ ] sampleValues = new int [ engine . numberOfInputVariables ( ) ] ; int [ ] minSampleValues = new int [ engine . numberOfInputVariables ( ) ] ; int [ ] maxSampleValues = new int [ engine . numberOfInputVariables ( ) ] ; for ( int i = 0 ; i < engine . numberOfInputVariables ( ) ; ++ i ) { sampleValues [ i ] = 0 ; minSampleValues [ i ] = 0 ; maxSampleValues [ i ] = resolution ; } this . expected = new ArrayList < double [ ] > ( ) ; do { double [ ] expectedValues = new double [ engine . numberOfInputVariables ( ) ] ; for ( int i = 0 ; i < engine . numberOfInputVariables ( ) ; ++ i ) { InputVariable inputVariable = engine . getInputVariable ( i ) ; expectedValues [ i ] = inputVariable . getMinimum ( ) + sampleValues [ i ] * inputVariable . range ( ) / Math . max ( 1 , resolution ) ; } this . expected . add ( expectedValues ) ; } while ( Op . increment ( sampleValues , minSampleValues , maxSampleValues ) ) ; }
|
Produces and loads into memory the set of expected values from the engine
|
39,985
|
public void prepare ( Reader reader , long numberOfLines ) throws IOException { this . expected = new ArrayList < double [ ] > ( ) ; BufferedReader bufferedReader = new BufferedReader ( reader ) ; try { String line ; int lineNumber = 0 ; while ( lineNumber != numberOfLines && ( line = bufferedReader . readLine ( ) ) != null ) { ++ lineNumber ; line = line . trim ( ) ; if ( line . isEmpty ( ) || line . charAt ( 0 ) == '#' ) { continue ; } double [ ] expectedValues ; if ( lineNumber == 1 ) { try { expectedValues = Op . toDoubles ( line ) ; } catch ( Exception ex ) { continue ; } } else { expectedValues = Op . toDoubles ( line ) ; } this . expected . add ( expectedValues ) ; } } catch ( IOException ex ) { throw ex ; } finally { bufferedReader . close ( ) ; } }
|
Reads and loads into memory the set of expected values from the engine
|
39,986
|
public double [ ] run ( int times ) { if ( engine == null ) { throw new RuntimeException ( "[benchmark error] engine not set for benchmark" ) ; } double [ ] runtimes = new double [ times ] ; final int offset = engine . getInputVariables ( ) . size ( ) ; for ( int t = 0 ; t < times ; ++ t ) { obtained = new ArrayList < double [ ] > ( expected . size ( ) ) ; for ( int i = 0 ; i < expected . size ( ) ; ++ i ) { obtained . add ( new double [ engine . numberOfInputVariables ( ) + engine . numberOfOutputVariables ( ) ] ) ; } engine . restart ( ) ; long start = System . nanoTime ( ) ; for ( int evaluation = 0 ; evaluation < expected . size ( ) ; ++ evaluation ) { double [ ] expectedValues = expected . get ( evaluation ) ; double [ ] obtainedValues = obtained . get ( evaluation ) ; if ( expectedValues . length < engine . getInputVariables ( ) . size ( ) ) { throw new RuntimeException ( MessageFormat . format ( "[benchmark error] the number of input values given <{0}> " + "at line <{1}> must be at least the same number of input variables " + "<{2}> in the engine" , expectedValues . length , evaluation + 1 , engine . numberOfInputVariables ( ) ) ) ; } for ( int i = 0 ; i < engine . getInputVariables ( ) . size ( ) ; ++ i ) { engine . getInputVariables ( ) . get ( i ) . setValue ( expectedValues [ i ] ) ; obtainedValues [ i ] = expectedValues [ i ] ; } engine . process ( ) ; for ( int i = 0 ; i < engine . getOutputVariables ( ) . size ( ) ; ++ i ) { obtainedValues [ i + offset ] = engine . getOutputVariables ( ) . get ( i ) . getValue ( ) ; } } long end = System . nanoTime ( ) ; runtimes [ t ] = end - start ; } for ( double x : runtimes ) { this . times . add ( x ) ; } return runtimes ; }
|
Runs the benchmark on the engine multiple times
|
39,987
|
public boolean canComputeErrors ( ) { return ! ( engine == null || expected . isEmpty ( ) || obtained . isEmpty ( ) || expected . size ( ) != obtained . size ( ) || expected . get ( 0 ) . length != obtained . get ( 0 ) . length || expected . get ( 0 ) . length != engine . variables ( ) . size ( ) ) ; }
|
Indicates whether errors can be computed based on the expected and obtained values from the benchmark . If the benchmark was prepared from a file reader and the file included columns of expected output values and the benchmark has been run at least once then the benchmark can automatically compute the errors and will automatically include them in the results .
|
39,988
|
public int numberOfErrors ( ErrorType errorType , OutputVariable outputVariable ) { if ( ! canComputeErrors ( ) ) { return - 1 ; } int errors = 0 ; final int offset = engine . numberOfInputVariables ( ) ; for ( int i = 0 ; i < expected . size ( ) ; ++ i ) { double [ ] e = expected . get ( i ) ; double [ ] o = obtained . get ( i ) ; for ( int y = 0 ; y < engine . numberOfOutputVariables ( ) ; ++ y ) { if ( outputVariable == null || outputVariable == engine . getOutputVariable ( y ) ) { if ( ! Op . isEq ( e [ offset + y ] , o [ offset + y ] , tolerance ) ) { double difference = e [ offset + y ] - o [ offset + y ] ; if ( errorType == ErrorType . Accuracy && Op . isFinite ( difference ) ) { ++ errors ; } else if ( errorType == ErrorType . NonFinite && ! Op . isFinite ( difference ) ) { ++ errors ; } else if ( errorType == ErrorType . All ) { ++ errors ; } } } } } return errors ; }
|
Computes the number of errors of the given type over the given output variable .
|
39,989
|
public double factorOf ( TimeUnit unit ) { if ( unit == TimeUnit . NanoSeconds ) { return 1.0 ; } else if ( unit == TimeUnit . MicroSeconds ) { return 1.0e-3 ; } else if ( unit == TimeUnit . MilliSeconds ) { return 1.0e-6 ; } else if ( unit == TimeUnit . Seconds ) { return 1.0e-9 ; } else if ( unit == TimeUnit . Minutes ) { return 1.0e-9 / 60 ; } else if ( unit == TimeUnit . Hours ) { return 1.0e-9 / 3600 ; } return Double . NaN ; }
|
Returns the factor of the given unit from NanoSeconds
|
39,990
|
public double convert ( double time , TimeUnit from , TimeUnit to ) { return time * factorOf ( to ) / factorOf ( from ) ; }
|
Converts the time to different scales
|
39,991
|
public Set < String > header ( int runs , boolean includeErrors ) { Benchmark result = new Benchmark ( ) ; Engine dummy = new Engine ( ) ; dummy . addOutputVariable ( new OutputVariable ( ) ) ; result . setEngine ( dummy ) ; Double [ ] dummyTimes = new Double [ runs ] ; Arrays . fill ( dummyTimes , Double . NaN ) ; result . setTimes ( Arrays . asList ( dummyTimes ) ) ; if ( includeErrors ) { double [ ] dummyArray = new double [ 1 ] ; List < double [ ] > dummyList = new ArrayList < double [ ] > ( ) ; dummyList . add ( dummyArray ) ; result . setExpected ( dummyList ) ; result . setObtained ( dummyList ) ; } return result . results ( ) . keySet ( ) ; }
|
Returns the header of a horizontal table of results
|
39,992
|
public Map < String , String > results ( TimeUnit timeUnit , boolean includeTimes ) { return results ( null , timeUnit , includeTimes ) ; }
|
Computes and returns the results from the benchmark aggregating the statistics of all the output variables
|
39,993
|
public void toFile ( File file , Engine engine ) throws IOException { if ( ! file . createNewFile ( ) ) { FuzzyLite . logger ( ) . log ( Level . FINE , "Replacing file: {0}" , file . getAbsolutePath ( ) ) ; } BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( file ) , FuzzyLite . UTF_8 ) ) ; try { writer . write ( toString ( engine ) ) ; } catch ( IOException ex ) { throw ex ; } finally { writer . close ( ) ; } }
|
Stores the string representation of the engine into the specified file
|
39,994
|
public String header ( Engine engine ) { List < String > result = new LinkedList < String > ( ) ; if ( exportInputValues ) { for ( InputVariable inputVariable : engine . getInputVariables ( ) ) { result . add ( inputVariable . getName ( ) ) ; } } if ( exportOutputValues ) { for ( OutputVariable outputVariable : engine . getOutputVariables ( ) ) { result . add ( outputVariable . getName ( ) ) ; } } return Op . join ( result , separator ) ; }
|
Gets the header of the dataset for the given engine
|
39,995
|
public Type inferType ( Term term ) { if ( term instanceof Constant || term instanceof Linear || term instanceof Function ) { return Type . TakagiSugeno ; } return Type . Tsukamoto ; }
|
Infers the type of the defuzzifier based on the given term . If the given term is Constant Linear or Function then the type is TakagiSugeno ; otherwise the type is Tsukamoto
|
39,996
|
public void defuzzify ( ) { if ( ! isEnabled ( ) ) { return ; } if ( Op . isFinite ( getValue ( ) ) ) { setPreviousValue ( getValue ( ) ) ; } String exception = null ; double result = Double . NaN ; boolean isValid = ! fuzzyOutput ( ) . getTerms ( ) . isEmpty ( ) ; if ( isValid ) { isValid = false ; if ( getDefuzzifier ( ) != null ) { try { result = getDefuzzifier ( ) . defuzzify ( fuzzyOutput ( ) , getMinimum ( ) , getMaximum ( ) ) ; isValid = true ; } catch ( Exception ex ) { exception = ex . toString ( ) ; } } else { exception = String . format ( "[defuzzifier error] defuzzifier needed " + "to defuzzify output variable <%s>" , getName ( ) ) ; } } if ( ! isValid ) { if ( isLockPreviousValue ( ) && ! Double . isNaN ( getPreviousValue ( ) ) ) { result = getPreviousValue ( ) ; } else { result = getDefaultValue ( ) ; } } setValue ( result ) ; if ( exception != null ) { throw new RuntimeException ( exception ) ; } }
|
Defuzzifies the output variable and stores the output value and the previous output value
|
39,997
|
public void loadRules ( Engine engine ) { List < String > exceptions = new ArrayList < String > ( ) ; for ( Rule rule : this . rules ) { if ( rule . isLoaded ( ) ) { rule . unload ( ) ; } try { rule . load ( engine ) ; } catch ( Exception ex ) { exceptions . add ( String . format ( "[%s]: %s" , rule . getText ( ) , ex . toString ( ) ) ) ; } } if ( ! exceptions . isEmpty ( ) ) { throw new RuntimeException ( "[ruleblock error] the following " + "rules could not be loaded:\n" + Op . join ( exceptions , "\n" ) ) ; } }
|
Loads all the rules into the rule block
|
39,998
|
public Direction direction ( ) { if ( direction > start ) { return Direction . Positive ; } if ( direction < start ) { return Direction . Negative ; } return Direction . Undefined ; }
|
Gets the Direction of the binary edge as an enumerator
|
39,999
|
public double membership ( double x ) { if ( Double . isNaN ( x ) ) { return Double . NaN ; } if ( implication == null ) { throw new RuntimeException ( String . format ( "[implication error] " + "implication operator needed to activate %s" , getTerm ( ) . toString ( ) ) ) ; } return implication . compute ( term . membership ( x ) , degree ) ; }
|
Computes the implication of the activation degree and the membership function value of x
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.