code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.joone.util; import java.beans.*; public class MinMaxExtractorPlugInBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( MinMaxExtractorPlugIn.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedSerieSelector = 0; private static final int PROPERTY_minChangePercentage = 1; private static final int PROPERTY_name = 2; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[3]; try { properties[PROPERTY_advancedSerieSelector] = new PropertyDescriptor ( "advancedSerieSelector", MinMaxExtractorPlugIn.class, "getAdvancedSerieSelector", "setAdvancedSerieSelector" ); properties[PROPERTY_minChangePercentage] = new PropertyDescriptor ( "minChangePercentage", MinMaxExtractorPlugIn.class, "getMinChangePercentage", "setMinChangePercentage" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", MinMaxExtractorPlugIn.class, "getName", "setName" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
/* * ColumnSelectorPlugIn.java * * Created on November 4, 2004, 4:26 PM */ package org.joone.util; import org.joone.engine.Pattern; import org.joone.log.*; /** * Certain plug-ins change the number of columns during their conversion, for example * the <code>ToBinaryPlugin</code> increases the number of columns. This plug in can * be used to select certain columns from all available columns at that moment. * It just uses an advanced column selector as <code>StreamInputSynapse</code> and * all plug-ins do, but this plug-in does not work on certain columns as most plug-ins * do, but it selects columns like the <code>StreamInputSynapse</code> does. * * @author Boris Jansen */ public class ColumnSelectorPlugIn extends ConverterPlugIn { /** The logger for this class. */ private static final ILogger log = LoggerFactory.getLogger(ColumnSelectorPlugIn.class); /** Creates a new instance of ColumnSelectorPlugIn */ public ColumnSelectorPlugIn() { } /** * Creates a new instance of ColumnSelectorPlugIn * * @param anAdvancedSerieSelector the advanced serie selector to use. * @see setAdvancedSerieSelector() */ public ColumnSelectorPlugIn(String anAdvancedSerieSelector) { super(anAdvancedSerieSelector); } protected boolean convert(int serie) { // do nothing, we select the columns in applyOnRows return false; } protected boolean applyOnRows() { boolean retValue = false; if (getAdvancedSerieSelector() != null && !getAdvancedSerieSelector().equals(new String(""))) { int [] mySerieSelected = getSerieSelected(); for(int i = 0; i < getInputVector().size(); i++) { double[] mySelected = new double[mySerieSelected.length]; Pattern myPattern = (Pattern)getInputVector().get(i); for(int j = 0; j < mySerieSelected.length; j++) { if(mySerieSelected[j] - 1 < myPattern.getArray().length) { // Check we don't go over array bounds. mySelected[j] = myPattern.getArray()[mySerieSelected[j] - 1]; } else { log.warn(getName() + " : Advanced Serie Selector contains too many serie. " + "Check the number of columns in the appropriate input synapse or previous plug in."); } } myPattern.setArray(mySelected); retValue = true; } } return retValue; } }
Java
package org.joone.util; import org.joone.engine.*; /** * Center around the zero all the time series subtracting its average * Creation date: (23/10/2000 23.55.34) * @author: Administrator */ public class CenterOnZeroPlugIn extends ConverterPlugIn { private static final long serialVersionUID = 8581778588210471901L; /** * CenterOnZeroPlugIn constructor comment. */ public CenterOnZeroPlugIn() { super(); } /** * Starts the convertion */ protected boolean convert(int serie) { boolean retValue = false; int s = getInputVector().size(); int i; double v; double d = 0; Pattern currPE; // Calculate average for (i = 0; i < s; ++i) d += getValuePoint(i, serie); d = d / s; // Shift average amount for (i = 0; i < s; ++i) { v = getValuePoint(i, serie); v = v - d; currPE = (Pattern) getInputVector().elementAt(i); currPE.setValue(serie, v); retValue = true; } return retValue; } }
Java
package org.joone.util; import org.joone.engine.*; import org.joone.net.*; import java.util.*; import java.io.*; import org.joone.log.*; /** * Abstract class that must be extended to implement plugins for output data preprocessing. * The objects extending this class can be inserted into objects that extend the * {@link org.joone.io.StreamOutputSynapse}. * * @author Julien Norman */ public abstract class OutputConverterPlugIn extends AbstractConverterPlugIn { /** For converting on a one pattern basis. */ private transient Pattern conv_pattern; private static final long serialVersionUID = 1698511686417967414L; /** The logger for this class. */ private static final ILogger log = LoggerFactory.getLogger( OutputConverterPlugIn.class ); /** * Constructor of CoverterPlugIn. */ public OutputConverterPlugIn() { } /** * Constructor of CoverterPlugIn. * * @param anAdvancedSerieSelector * @see AbstractConverterPlugIn#AbstractConverterPlugIn(String) */ public OutputConverterPlugIn(String anAdvancedSerieSelector) { super(anAdvancedSerieSelector); } /** * Applies the preprocessing on the Nth serie of the data. This method should be * implemented in classes that extend this one. * * @param serie the serie to be converted */ protected abstract void convert_pattern(int serie); /** * Applies the preprocessing on the patterns contained in the conv_patterns */ public void convertPattern() throws NumberFormatException { // Use Advanced Serie Selector to select the serie to convert if((getAdvancedSerieSelector() != null ) && (!getAdvancedSerieSelector().equals(new String(""))) ) { try { int [] mySerieSelected = getSerieSelected(); for(int i = 0; i < mySerieSelected.length; i++) { convert_pattern(mySerieSelected[i]-1); } } catch (NumberFormatException nfe) { throw new NumberFormatException(nfe.getMessage()); } } else log.warn(getName()+" : Advanced Serie Selector not populated therefore converting no data."); // Recurrent call to other connected plugins if (getNextPlugIn() != null) { OutputConverterPlugIn myPlugIn = (OutputConverterPlugIn)getNextPlugIn(); myPlugIn.setPattern(getPattern()); myPlugIn.convertPattern(); } } /** * Applies the preprocessing on the pattern contained in the conv_pattern * @deprecated Use {@link AbstractConverterPlugIn#convertPatterns()} */ public void convertAllPatterns() throws NumberFormatException { convertPatterns(); } /** * Gets the pattern that will be converted. * @return the Pattern to convert when in unbuffered mode */ protected Pattern getPattern() { return conv_pattern; } /** Sets the current pattern to convert. * @param newPattern The pattern that should be converted by this plugin. */ public void setPattern(Pattern newPattern) { conv_pattern = newPattern; } /** * @deprecated Use {@link AbstractConverterPlugIn#addPlugInListener(PlugInListener)} */ public synchronized void addOutputPluginListener(OutputPluginListener aListener) { addPlugInListener(aListener); } /** * @deprecated Use {@link AbstractConverterPlugIn#removePlugInListener(PlugInListener)} */ public synchronized void removeOutputPluginListener(OutputPluginListener aListener) { removePlugInListener(aListener); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // To maintain the compatibility with the old saved classes if (getAdvancedSerieSelector() == null) setAdvancedSerieSelector(new String("1")); if (getName() == null) setName("OutputPlugin 9"); } }
Java
package org.joone.util; import java.beans.*; public class ShufflePluginBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( ShufflePlugin.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_name = 0; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[1]; try { properties[PROPERTY_name] = new PropertyDescriptor ( "name", ShufflePlugin.class, "getName", "setName" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.util; import java.beans.*; public class NormalizerPlugInBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( NormalizerPlugIn.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedSerieSelector = 0; private static final int PROPERTY_dataMax = 1; private static final int PROPERTY_dataMin = 2; private static final int PROPERTY_max = 3; private static final int PROPERTY_min = 4; private static final int PROPERTY_name = 5; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[6]; try { properties[PROPERTY_advancedSerieSelector] = new PropertyDescriptor ( "advancedSerieSelector", NormalizerPlugIn.class, "getAdvancedSerieSelector", "setAdvancedSerieSelector" ); properties[PROPERTY_dataMax] = new PropertyDescriptor ( "dataMax", NormalizerPlugIn.class, "getDataMax", "setDataMax" ); properties[PROPERTY_dataMax].setDisplayName ( "InputDataMax" ); properties[PROPERTY_dataMin] = new PropertyDescriptor ( "dataMin", NormalizerPlugIn.class, "getDataMin", "setDataMin" ); properties[PROPERTY_dataMin].setDisplayName ( "InputDataMin" ); properties[PROPERTY_max] = new PropertyDescriptor ( "max", NormalizerPlugIn.class, "getMax", "setMax" ); properties[PROPERTY_max].setDisplayName ( "OutputDataMax" ); properties[PROPERTY_min] = new PropertyDescriptor ( "min", NormalizerPlugIn.class, "getMin", "setMin" ); properties[PROPERTY_min].setDisplayName ( "OutputDataMin" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", NormalizerPlugIn.class, "getName", "setName" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.util; /** * @deprecated Use {@link PlugInEvent} */ public class OutputPluginEvent extends PlugInEvent { public OutputPluginEvent(AbstractConverterPlugIn aPlugIn) { super(aPlugIn); } }
Java
package org.joone.util; /** * @deprecated Use {@link PlugInEvent} */ public class InputPluginEvent extends PlugInEvent { public InputPluginEvent(AbstractConverterPlugIn aPlugIn) { super(aPlugIn); } }
Java
package org.joone.util; import java.beans.*; public class OutputConverterPlugInBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( OutputConverterPlugIn.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedSerieSelector = 0; private static final int PROPERTY_name = 1; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[2]; try { properties[PROPERTY_advancedSerieSelector] = new PropertyDescriptor ( "advancedSerieSelector", OutputConverterPlugIn.class, "getAdvancedSerieSelector", "setAdvancedSerieSelector" ); properties[PROPERTY_advancedSerieSelector].setDisplayName ( "Advanced Serie Selector" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", OutputConverterPlugIn.class, "getName", "setName" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
/* * LearningSwitch.java * * Created on 30 aprile 2002, 16.10 */ package org.joone.util; import org.joone.engine.*; import org.joone.io.*; import org.joone.net.NetCheck; import java.util.TreeSet; /** * This class is useful to switch the input data set of a neural network * from a training set to a validation set depending on the 'validation' * parameter contained in the Monitor object. * Very useful during a training phase to test the generalization capacity * of the neural network with a validation data set never seen before. * * @author pmarrone */ public class LearningSwitch extends InputSwitchSynapse { private StreamInputSynapse trainingSet; private StreamInputSynapse validationSet; private boolean validation = false; private static final long serialVersionUID = -2339515807277374407L; /******* Not more used. * They are here only to maintain the compatibility with the old * serialized classes. * Use instead the patterns/validationPatterns parameters of the * Monitor object. ********/ private int validationPatterns; // Not more used private int trainingPatterns; // Not more used /** Creates a new instance of LearningSwitch */ public LearningSwitch() { super(); } public synchronized boolean addTrainingSet(StreamInputSynapse tSet) { if (trainingSet != null) return false; // super.removeInputSynapse(trainingSet.getName()); if (super.addInputSynapse(tSet)) { trainingSet = tSet; // The training set is the default input data set super.setDefaultSynapse(trainingSet); super.reset(); validation = false; return true; } else return false; } public synchronized boolean addValidationSet(StreamInputSynapse vSet) { if (validationSet != null) return false; // super.removeInputSynapse(validationSet.getName()); if (super.addInputSynapse(vSet)) { validationSet = vSet; return true; } else return false; } public synchronized void removeTrainingSet() { if (trainingSet != null) { super.removeInputSynapse(trainingSet.getName()); trainingSet = null; } } public synchronized void removeValidationSet() { if (validationSet != null) { super.removeInputSynapse(validationSet.getName()); validationSet = null; } } /** Connects the right input synapse depending on the * Monitor's 'validation' parameter * @return neural.engine.Pattern */ public Pattern fwdGet() { if (getMonitor().isValidation() && !getMonitor().isTrainingDataForValidation()) super.setActiveSynapse(validationSet); else super.setActiveSynapse(trainingSet); return super.fwdGet(); } /** Connects the right input synapse depending on the * Monitor's 'validation' parameter. Added to be * compatible with the InputConnector class. * @return neural.engine.Pattern */ public Pattern fwdGet(InputConnector conn) { /** Connects the right input synapse depending on the * Monitor's 'validation' parameter * @return neural.engine.Pattern */ if (getMonitor().isValidation() && !getMonitor().isTrainingDataForValidation()) super.setActiveSynapse(validationSet); else super.setActiveSynapse(trainingSet); return super.fwdGet(conn); } public java.util.TreeSet check() { TreeSet checks = super.check(); // Check that the first row is greater than 0. if (trainingSet == null) { checks.add(new NetCheck(NetCheck.FATAL, "Training set parameter not set", this)); } if (validationSet == null) { checks.add(new NetCheck(NetCheck.FATAL, "Validation set parameter not set", this)); } return checks; } /** * Getter for property trainingSet. * Added for XML serialization * @return Value of property trainingSet. */ public org.joone.io.StreamInputSynapse getTrainingSet() { return trainingSet; } /** * Setter for property trainingSet. * Added for XML serialization * @param trainingSet New value of property trainingSet. */ public void setTrainingSet(org.joone.io.StreamInputSynapse trainingSet) { this.trainingSet = trainingSet; } /** * Getter for property validationSet. * Added for XML serialization * @return Value of property validationSet. */ public org.joone.io.StreamInputSynapse getValidationSet() { return validationSet; } /** * Setter for property validationSet. * Added for XML serialization * @param validationSet New value of property validationSet. */ public void setValidationSet(org.joone.io.StreamInputSynapse validationSet) { this.validationSet = validationSet; } }
Java
package org.joone.util; import java.beans.PropertyEditorSupport; /** * A property editor for the <code>format</code> property * of a <code>SnapshotRecorder</code> plugin. * * @see org.joone.util.SnapshotRecorder * * @author Olivier Hussenet */ public class SnapshotFormatEditor extends PropertyEditorSupport { /** The supported snapshot formats */ public final String [] formats = { /*SnapshotRecorder.VISAD_FORMAT,*/ SnapshotRecorder.JOONE_FORMAT }; /** * Get an array of legal string values. * * @return an array of all legal string values */ public String [] getTags () { return formats; } }
Java
package org.joone.util; import java.beans.*; public class UnNormalizerOutputPlugInBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( UnNormalizerOutputPlugIn.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedSerieSelector = 0; private static final int PROPERTY_inDataMax = 1; private static final int PROPERTY_inDataMin = 2; private static final int PROPERTY_name = 3; private static final int PROPERTY_outDataMax = 4; private static final int PROPERTY_outDataMin = 5; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[6]; try { properties[PROPERTY_advancedSerieSelector] = new PropertyDescriptor ( "advancedSerieSelector", UnNormalizerOutputPlugIn.class, "getAdvancedSerieSelector", "setAdvancedSerieSelector" ); properties[PROPERTY_advancedSerieSelector].setDisplayName ( "Advanced Serie Selector" ); properties[PROPERTY_inDataMax] = new PropertyDescriptor ( "inDataMax", UnNormalizerOutputPlugIn.class, "getInDataMax", "setInDataMax" ); properties[PROPERTY_inDataMin] = new PropertyDescriptor ( "inDataMin", UnNormalizerOutputPlugIn.class, "getInDataMin", "setInDataMin" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", UnNormalizerOutputPlugIn.class, "getName", "setName" ); properties[PROPERTY_outDataMax] = new PropertyDescriptor ( "outDataMax", UnNormalizerOutputPlugIn.class, "getOutDataMax", "setOutDataMax" ); properties[PROPERTY_outDataMin] = new PropertyDescriptor ( "outDataMin", UnNormalizerOutputPlugIn.class, "getOutDataMin", "setOutDataMin" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
/* Joone */ package org.joone.util; /** * @deprecated Use {@link PlugInListener} */ public interface InputPluginListener extends PlugInListener { }
Java
/* Joone */ package org.joone.util; /** * @deprecated Use {@link PlugInListener} */ public interface OutputPluginListener extends PlugInListener { }
Java
package org.joone.util; import org.joone.engine.*; import org.joone.script.*; public class GroovyMacroPlugin extends MonitorPlugin implements MacroInterface { static final long serialVersionUID = -4123807261022916301L; private transient JooneGroovyScript jScript; private MacroManager macroManager; public GroovyMacroPlugin() { } public void set(String name, Object jObject){ getGroovy().set(name, jObject); } private JooneGroovyScript getGroovy() { if (jScript == null) { jScript = new JooneGroovyScript(); } return jScript; } protected void manageStart(Monitor mon) { getGroovy().set("jMon", mon); String macro = getMacroManager().getMacro("netStarted"); runScript(macro, false); } protected void manageCycle(Monitor mon) { //Pass monitor object to script instance to allow access to monitor methods getGroovy().set("jMon", mon); String macro = getMacroManager().getMacro("cycleTerminated"); runScript(macro, false); } protected void manageStop(Monitor mon) { getGroovy().set("jMon", mon); String macro = getMacroManager().getMacro("netStopped"); runScript(macro, false); } protected void manageError(Monitor mon) { getGroovy().set("jMon", mon); String macro = getMacroManager().getMacro("errorChanged"); runScript(macro, false); } /** Run a generic macro contained in a text * @parameter the text of the macro */ public void runMacro(String text) { runScript(text, false); } private void runScript(String eventScript, boolean file){ if (file){ jScript.source(eventScript); } else { jScript.eval(eventScript); } } /** Getter for property macroManager. * @return Value of property macroManager. */ public MacroManager getMacroManager() { if (macroManager == null) macroManager = new MacroManager(); return macroManager; } /** Setter for property macroManager. * @param macroManager New value of property macroManager. */ public void setMacroManager(MacroManager macroManager) { this.macroManager = macroManager; } protected void manageStopError(Monitor mon, String msgErr) { } }
Java
package org.joone.util; import org.joone.engine.Monitor; import org.joone.net.NeuralNet; /** * A SnapshotPlugin manages the generation of snapshots of the network's state * at regular intervals during its activity. The effective snapshot generation * is deferred to subclasses to allow for misc. storage formats and output * destinations. * * @author Olivier Hussenet */ public abstract class SnapshotPlugin extends MonitorPlugin implements java.io.Serializable { private static final long serialVersionUID = -4796324031568433167L; /** * Creates a new SnapshotPlugin object. */ protected SnapshotPlugin () { super(); // Initialize default rate setRate (100); } /** * Start a new activity session: calls the doStart method to inform * subclasses, then generates a snapshot of the initial state of the * network. * * @param mon the monitor */ protected final void manageStart (Monitor mon) { // Check for activation (rate > 0) if (getRate () == 0) return; // Start snapshots generation doStart (); // Generates a snapshot of the initial state of the network doSnapshot (); } /** * Allows subclasses to define specific start processing. * * @param net the current neural network. */ protected abstract void doStart (); /** * Process one cycle of activity: calls the doSnapshot method to allow for * specific snapshot generation by subclasses. * * @param mon the monitor */ protected final void manageCycle (Monitor mon) { doSnapshot (); } /** * Allows subclasses to define specific snapshot generation. * * @param net the current neural network. */ protected abstract void doSnapshot (); /** * Stop an activity session: take a snapshot of the final state of the * network, then calls the doStop method to inform subclasses * * @param mon the monitor */ protected final void manageStop (Monitor mon) { // Check for activation (rate > 0) if (getRate () == 0) return; // Generate last snapshot, if necessary int current = mon.getTotCicles () - mon.getCurrentCicle (); if ((current % getRate ()) != 0) doSnapshot (); // Stop snapshots recording doStop (); } /** * Allows subclasses to define specific stop processing. * * @param net the current neural network. */ protected abstract void doStop (); /** * Global error is stored along with the monitor, so this method does * nothing. * * @param mon the monitor */ protected final void manageError (Monitor mon) { } }
Java
/* * DeltaNormPlugin.java * * Created on September 10, 2004, 11:13 AM */ package org.joone.util; import org.joone.engine.Pattern; /** * This plugin calculates the Delta Normalization on a time series. * the Delta Normalization technique permits to feed a neural network * with the delta values instead of the absolute values of the series, * permitting in this manner to avoid the problems correlated with both * ascending and descending trends. * The normalization is obtained by dividing the delta value by * the dynamic range (named Probability Volatility Windows) calculated * on the given period. This plugin is very useful for financial predictions * when used in combination with the MinMaxExtractorPlugin. * To learn more on this technique read the excellent book: * "Financial Prediction Using Neural Networks" by Joseph S. Zirilli * (you can buy it in electronic format at http://www.mjfutures.com/Book.htm) * * @author P.Marrone */ public class DeltaNormPlugIn extends ConverterPlugIn { private static final long serialVersionUID = 1698511686417955514L; private transient double[] probVolWin; // Probablity Volatility Window /** Creates a new instance of DeltaNormPlugin */ public DeltaNormPlugIn() { } protected boolean convert(int serie) { boolean retValue = false; int currInput = getSerieIndexNumber(serie); if (getProbVolWin()[currInput] == 0) getProbVolWin()[currInput] = calculatePVW(currInput+1, serie); int init = getSerieSelected().length; for (int i=getInputVector().size()-1; i >= init ; --i) { double vi = getDelta(i, currInput+1, serie, false); vi /= getProbVolWin()[currInput]; Pattern currPE = (Pattern) getInputVector().elementAt(i); currPE.setValue(serie, vi); retValue = true; } return retValue; } /* Calculates the Probability Volatility Windows for the serie * pvw = 2 * avg(sum[]((Ci - f(delay,i))/Ci)) */ protected double calculatePVW(int delay, int serie) { int init = getSerieSelected().length; double sum = 0; for (int i=init; i < getInputVector().size(); ++i) { sum += getDelta(i, delay, serie, true); } int numPoints = getInputVector().size() - init; sum = sum / numPoints; // Average return sum * 2; } /* Calculates the formula (Ci - f(i,delay))/Ci */ protected double getDelta(int index, int delay, int serie, boolean abs) { double Ci = getValuePoint(index, serie); double fd = funcDelta(index, delay, serie); if (Ci == 0) { if (!abs) return -fd/Math.abs(fd); else return fd/fd; } if (!abs) return (Ci - fd)/Ci; else return Math.abs(Ci-fd)/Ci; } /** Calculates f(i,delay) used by getDelta * >>>> This method can be overriden in order to implement * different volatility window algorithms */ protected double funcDelta(int index, int delay, int serie) { return getValuePoint(index - delay, serie); } /** * Getter for property probVolWin, the * array containing the Probability Volatility Window * @return Value of property probVolWin. */ private double[] getProbVolWin() { if ((probVolWin == null) || (probVolWin.length != getSerieSelected().length)) { probVolWin = new double[getSerieSelected().length]; } return this.probVolWin; } }
Java
/* * ShufflePlugin.java * * Created on 11 febbraio 2004, 14.59 */ package org.joone.util; import org.joone.engine.Pattern; /** This plugin shuffles the content of the input buffer * by mixing randomly the rows. * * @author P.Marrone */ public class ShufflePlugin extends ConverterPlugIn { static final long serialVersionUID = 7118539833128121178L; /** Creates a new instance of ShufflePlugin */ public ShufflePlugin() { setApplyEveryCycle(true); setAdvancedSerieSelector("1"); } protected boolean convert(int serie) { // We don't need to apply any conversion to the columns return false; } protected boolean applyOnRows() { boolean retValue = false; int s = getInputVector().size(); for (int i=0; i < s; ++i) { int n = i; while (n == i) { // Extracts an integer between 0 and s - 1 n = Math.round((float)(Math.random() * s)); n = (n > 0) ? n - 1: 0; } // Now exchanges the elements at n,i Pattern p1 = (Pattern)getInputVector().elementAt(i); Pattern p2 = (Pattern)getInputVector().elementAt(n); getInputVector().set(n, p1); getInputVector().set(i, p2); retValue = true; } return retValue; } }
Java
package org.joone.util; import org.joone.engine.*; import org.joone.script.*; public class MacroPlugin extends MonitorPlugin implements MacroInterface { static final long serialVersionUID = -4867807261022916301L; private transient JooneScript jScript; private MacroManager macroManager; public MacroPlugin() { } public void set(String name, Object jObject){ getBSH().set(name, jObject); } private JooneScript getBSH() { if (jScript == null) { jScript = new JooneScript(); } return jScript; } protected void manageStart(Monitor mon) { getBSH().set("jMon", mon); String macro = getMacroManager().getMacro("netStarted"); runScript(macro, false); } protected void manageCycle(Monitor mon) { //Pass monitor object to script instance to allow access to monitor methods getBSH().set("jMon", mon); String macro = getMacroManager().getMacro("cycleTerminated"); runScript(macro, false); } protected void manageStop(Monitor mon) { getBSH().set("jMon", mon); String macro = getMacroManager().getMacro("netStopped"); runScript(macro, false); } protected void manageError(Monitor mon) { getBSH().set("jMon", mon); String macro = getMacroManager().getMacro("errorChanged"); runScript(macro, false); } /** Run a generic macro contained in a text * @parameter the text of the macro */ public void runMacro(String text) { runScript(text, false); } private void runScript(String eventScript, boolean file){ if (file){ jScript.source(eventScript); } else { jScript.eval(eventScript); } } /** Getter for property macroManager. * @return Value of property macroManager. */ public MacroManager getMacroManager() { if (macroManager == null) macroManager = new MacroManager(); return macroManager; } /** Setter for property macroManager. * @param macroManager New value of property macroManager. */ public void setMacroManager(MacroManager macroManager) { this.macroManager = macroManager; } protected void manageStopError(Monitor mon, String msgErr) { } }
Java
package org.joone.util; import org.joone.net.NeuralNet; import org.joone.net.NeuralNetLoader; import org.joone.engine.NeuralNetListener; import org.joone.engine.NeuralNetEvent; import org.joone.engine.Monitor; import java.io.*; /** */ public class NeuralNetRunner implements NeuralNetListener { public NeuralNet nnet; public int result = 0; private String snetFileName; private String snetOutputFileName; private long lPrintCicle = 1000; public NeuralNetRunner() { } public static void main(String args[]) { NeuralNetRunner nnRunner = new NeuralNetRunner(); if (args.length < 1) { System.out.println("Usage: java NeuralNetRunner -snet <snetFile> [-printcicle <integer>] -snetout <snetOutputFile"); System.out.println("where <snetFile> is the Serialized Output from Joone Edit"); System.out.println("where <integer> is the Multiple of cicles output should be printed to standard output"); System.out.println("where <snetOutputFile> is filename for NeuralNetRunner to save the NeurlalNet as it is processing."); System.exit(1); } else { for (int n = 0; n < args.length; n++) { if (args[n].equals("-snet")) { nnRunner.snetFileName = args[++n]; } else if (args[n].equals("-printcicle")) { nnRunner.lPrintCicle = Long.parseLong(args[++n]); } else if (args[n].equals("-snetout")) { nnRunner.snetOutputFileName = args[++n]; } else { throw new IllegalArgumentException("Unknown argument."); } } } if (nnRunner.snetFileName == null) { System.out.println("ERROR: A snet input parameter is required to run"); System.exit(1); } else if (nnRunner.snetFileName.equals(nnRunner.snetOutputFileName)) { System.out.println("ERROR: The output snet should not be the same as the input snet ."); System.exit(1); } NeuralNetLoader nnl = new NeuralNetLoader(nnRunner.snetFileName); nnRunner.setNnet(nnl.getNeuralNet()); nnRunner.execute(); } public void execute() { if (nnet != null) { /* First of all, registers itself as neural net's listner, * so it can receive all the training events. */ nnet.getMonitor().addNeuralNetListener(this); // Runs the neural network's training cycles nnet.start(); nnet.getMonitor().Go(); /* Waits for the end of the training cycles */ synchronized(this) { try { while (result == 0) wait(); } catch (InterruptedException ie) { ie.printStackTrace(); } } } else throw new RuntimeException("Can't work: the neural net is null"); } public void cicleTerminated(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); long c = mon.getCurrentCicle(); long cl = c / lPrintCicle; /* We want print the results every lPrintCicle cycles */ if ((cl * lPrintCicle) == c) { System.out.println(c + " cycles remaining - Error = " + mon.getGlobalError()); writeNnet(); } } public void netStopped(NeuralNetEvent e) { synchronized(this) { // Notify the thread that the NN is finished result = 1; // Notifies the waiting threads notifyAll(); } } public void writeNnet() { if (snetOutputFileName != null) { try { FileOutputStream stream = new FileOutputStream(snetOutputFileName); ObjectOutput output = new ObjectOutputStream(stream); output.writeObject(nnet); output.close(); } catch (IOException ioe) { System.err.println("Error writing nnet: " + ioe); } } } public NeuralNet getNnet() { return nnet; } public void setNnet(NeuralNet nnet) { this.nnet = nnet; } public void resetNnet() { nnet.resetInput(); } public void netStarted(NeuralNetEvent e) { System.out.println("Running..."); } public void errorChanged(NeuralNetEvent e) { } public void netStoppedError(NeuralNetEvent e,String error) { } }
Java
package org.joone.util; import org.joone.engine.*; /** * This plugin changes linearly the values of the learning rate and of the momentum parameters. * The values go from an initial value to a final value linearly and the step is determined * by the formula: step = (FinalValue - InitValue) / numEphocs * Creation date: (26/10/2000 23.47.58) * @author: pmarrone */ public class LinearAnnealing extends MonitorPlugin { private double learningRateInitial; private double learningRateFinal; private double momentumInitial; private double momentumFinal; private static final long serialVersionUID = -3786770944656325519L; /** * Insert the method's description here. * Creation date: (26/10/2000 23.49.52) * @return double */ public double getLearningRateFinal() { return learningRateFinal; } /** * Insert the method's description here. * Creation date: (26/10/2000 23.49.26) * @return double */ public double getLearningRateInitial() { return learningRateInitial; } /** * Insert the method's description here. * Creation date: (26/10/2000 23.50.29) * @return double */ public double getMomentumFinal() { return momentumFinal; } /** * Insert the method's description here. * Creation date: (26/10/2000 23.50.14) * @return double */ public double getMomentumInitial() { return momentumInitial; } /** * Insert the method's description here. * Creation date: (26/10/2000 23.49.52) * @param newLearningRateFinal double */ public void setLearningRateFinal(double newLearningRateFinal) { learningRateFinal = newLearningRateFinal; } /** * Insert the method's description here. * Creation date: (26/10/2000 23.49.26) * @param newLearningRateInitial double */ public void setLearningRateInitial(double newLearningRateInitial) { learningRateInitial = newLearningRateInitial; } /** * Insert the method's description here. * Creation date: (26/10/2000 23.50.29) * @param newMomentumFinal double */ public void setMomentumFinal(double newMomentumFinal) { momentumFinal = newMomentumFinal; } /** * Insert the method's description here. * Creation date: (26/10/2000 23.50.14) * @param newMomentumInitial double */ public void setMomentumInitial(double newMomentumInitial) { momentumInitial = newMomentumInitial; } protected void manageCycle(Monitor mon) { double stepLR = (getLearningRateInitial() - getLearningRateFinal()) / mon.getTotCicles(); double stepMom = (getMomentumInitial() - getMomentumFinal()) / mon.getTotCicles(); int currCicle = mon.getTotCicles() - mon.getCurrentCicle(); mon.setLearningRate(getLearningRateInitial() - (stepLR * currCicle)); mon.setMomentum(getMomentumInitial() - (stepMom * currCicle)); } protected void manageStop(Monitor mon) { } protected void manageStart(Monitor mon) { } protected void manageError(Monitor mon) { } protected void manageStopError(Monitor mon, String msgErr) { } }
Java
/* * DeltaNormPlugInBeanInfo.java * * Created on 10 settembre 2004, 22.37 */ package org.joone.util; import java.beans.*; /** * @author paolo */ public class DeltaNormPlugInBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( DeltaNormPlugIn.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedSerieSelector = 0; private static final int PROPERTY_name = 1; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[2]; try { properties[PROPERTY_advancedSerieSelector] = new PropertyDescriptor ( "advancedSerieSelector", DeltaNormPlugIn.class, "getAdvancedSerieSelector", "setAdvancedSerieSelector" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", DeltaNormPlugIn.class, "getName", "setName" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.util; import org.joone.engine.*; /** * logarithmic transfer (base e) input data * Creation date: (22/03/2004 23.06.00) * @author: yccheok * */ public class LogarithmicPlugIn extends ConverterPlugIn { private static final long serialVersionUID = 4662839350631574552L; /** * LogarithmicPlugIn constructor */ public LogarithmicPlugIn() { super(); } /** * Start the convertion */ protected boolean convert(int serie) { int s = getInputVector().size(); double v = 0, result = 0; Pattern currPE = null; for(int i=0; i<s; ++i) { v = getValuePoint(i, serie); currPE = (Pattern) getInputVector().elementAt(i); if (v >= 0) result = Math.log(1 + v); else result = -Math.log(1 - v); currPE.setValue(serie, result); } return true; } }
Java
/* * MonitorLRManager.java * * Created on 1 febbraio 2002, 17.06 */ package org.joone.util; import org.joone.log.*; import org.joone.engine.Monitor; /** * This plugin controls the change of the learning rate based on the difference * between the last two global error (E) values: * if E(t) > E(t-1) then LR = LR * (1 - step/100) * Note: step/100 because step is inserted as a % value from the user * if E(t) <= E(t-1) then LR is unchanged * * @author pmarrone */ public class DynamicAnnealing extends MonitorPlugin { private static final ILogger log = LoggerFactory.getLogger (DynamicAnnealing.class); private double lastError = 0.0; private double step = 0.0; private static final long serialVersionUID = -5494365758818313237L; /** Creates a new instance of DynamicAnnealing */ public DynamicAnnealing() { super(); } protected void manageCycle(Monitor mon) { double actError = mon.getGlobalError(); if ((actError > lastError) && (lastError > 0.0) && (step > 0.0)) { double err = mon.getLearningRate() * (1 - step/100); mon.setLearningRate(err); int currentCycle = mon.getTotCicles() - mon.getCurrentCicle() + 1; log.info ("DynamicAnnealing: changed the learning rate to " + err + " at cycle n." + currentCycle); } lastError = actError; } protected void manageStop(Monitor mon) { } /** Getter for property step. * @return Value of property step. */ public double getStep() { return step; } /** Setter for property step. * @param step New value of property step. */ public void setStep(double step) { this.step = step; if (step >= 100) this.step = 99; } protected void manageStart(Monitor mon) { } protected void manageError(Monitor mon) { } protected void manageStopError(Monitor mon, String msgErr) { } }
Java
/* * RbfRandomCenterSelector.java * * Created on August 11, 2004, 5:31 PM */ package org.joone.util; import java.util.*; import org.joone.engine.*; import org.joone.log.*; /** * This plug in is used to select fixed centers for Gaussian RBF layers randomly * from the input data. Therefore, I implemented the selector as a plug in, * because this way I can easily select centers randomly from the input. * * @author Boris Jansen */ public class RbfRandomCenterSelector extends ConverterPlugIn { /** The logger. */ private static final ILogger log = LoggerFactory.getLogger(RbfRandomCenterSelector.class); /** The RBF layer (to get the number of neurons). */ private RbfGaussianLayer theRbfGaussianLayer; /** Save the input vectors. */ private Vector thePatterns = null; /** * Creates a new instance of RbfRandomCenterSelector * * @param aRbfGaussianLayer the RBF Gaussian layer to get the number of nodes. */ public RbfRandomCenterSelector(RbfGaussianLayer aRbfGaussianLayer) { theRbfGaussianLayer = aRbfGaussianLayer; setAdvancedSerieSelector("1"); } protected boolean convert(int serie) { // do nothing, we don't convert any data... // just save the input vectors if(thePatterns == null) { thePatterns = (Vector)getInputVector(); } return false; } /** * Gets the parameters for the different nodes in a RBF layer. * * @return the parameters for the different nodes in a RBF layer. */ public RbfGaussianParameters[] getGaussianParameters() { // There should be no plug ins after this plug in that convert data, // otherwise nonsense centers are selected... if(thePatterns.size() < theRbfGaussianLayer.getRows()) { log.warn("There are more neurons in RBF layer than training patterns -> " + "not all nodes in RBF layer will be assigned a unique center."); } int[] myCenters = new int[theRbfGaussianLayer.getRows()]; for(int i = 0; i < theRbfGaussianLayer.getRows(); i++) { int myCenter = (int)(Math.random() * thePatterns.size()); if(i < thePatterns.size()) { // there exist a non-selected center boolean myNonSelected = true; do { if(!myNonSelected) { // the selected center is already selected //myCenter = (myCenter + 1) % thePatterns.size(); // THIS IS NOT RANDOM myCenter = (int)(Math.random() * thePatterns.size()); myNonSelected = true; } for(int j = 0; j < i; j++) { if(myCenters[j] == myCenter) { myNonSelected = false; } } } while(!myNonSelected); } myCenters[i] = myCenter; } double myD = getMaxDistance(thePatterns, myCenters); // the following definition of the standard deviation ensures that the Gaussian // functions are not too peaked or too flat; both extremes are to be avoided. double myStdDeviation = myD / Math.sqrt(2 * theRbfGaussianLayer.getRows()); RbfGaussianParameters[] myParameters = new RbfGaussianParameters[theRbfGaussianLayer.getRows()]; for(int i = 0; i < theRbfGaussianLayer.getRows(); i++) { double[] myCenter = (double[])((Pattern)thePatterns.get(myCenters[i])).getArray().clone(); myParameters[i] = new RbfGaussianParameters(myCenter, myStdDeviation); // info /* String myText = "Gaussian Parameters [StdDeviation:" + myStdDeviation + ", center:"; for(int j = 0; j < myCenter.length; j++) { myText += myCenter[j]; if(j != myCenter.length-1) { myText += ","; } else { myText += "]"; } } log.info(myText); */ } return myParameters; } /** * Gets the maximum distance between centers. * * @param aPatterns all the input patterns (which might have been selected * to become a center). * @param anIndexes the indexes of the selected centers. */ protected double getMaxDistance(Vector aPatterns, int[] anIndexes) { double myMax = -1.0; double myDistance; for(int i = 0; i < anIndexes.length - 1; i++) { for(int j = i + 1; j < anIndexes.length; j++) { myDistance = getDistance((Pattern)aPatterns.get(anIndexes[i]), (Pattern)aPatterns.get(anIndexes[j])); if(myDistance > myMax) { myMax = myDistance; } } } return myMax; } /** * Gets the distance between two centers. * * @param aCenter1 the first center. * @param aCenter2 the second center. * @return the distance between the two centers. */ protected double getDistance(Pattern aCenter1, Pattern aCenter2) { double myDistance = 0; for(int i = 0; i < aCenter1.getArray().length; i++) { double myDiff = aCenter1.getArray()[i] - aCenter2.getArray()[i]; myDistance += myDiff * myDiff; } return Math.sqrt(myDistance); } }
Java
package org.joone.util; import java.beans.*; public class ConverterPlugInBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( ConverterPlugIn.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedSerieSelector = 0; private static final int PROPERTY_applyEveryCycle = 1; private static final int PROPERTY_name = 2; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[3]; try { properties[PROPERTY_advancedSerieSelector] = new PropertyDescriptor ( "advancedSerieSelector", ConverterPlugIn.class, "getAdvancedSerieSelector", "setAdvancedSerieSelector" ); properties[PROPERTY_applyEveryCycle] = new PropertyDescriptor ( "applyEveryCycle", ConverterPlugIn.class, "isApplyEveryCycle", "setApplyEveryCycle" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", ConverterPlugIn.class, "getName", "setName" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.util; import org.joone.engine.*; /** * Extracts from the time series the inversion points, setting its range * from MIN_VALUE to MAX_VALUE. * Example: * Input series: (doesn't matter the range of the input values) * /\ * /\ / \/ * / \/ * / * * Output series: (normalized in the range MIN_VALUE - MAX_VALUE) * MAX_VALUE------------ * /\ /\ * / \ / \ * / \/ \/ * MIN_VALUE------------ * * (29/09/00 13.47.22) * @author: Administrator */ public class MinMaxExtractorPlugIn extends ConverterPlugIn { private final double MIN_VALUE = 0.05; private final double MAX_VALUE = 0.95; private final double MID_VALUE = (MAX_VALUE - MIN_VALUE) / 2 + MIN_VALUE; private double minPerc = 0.01; private static final long serialVersionUID = 6835532403570359948L; class PointValue { double value; int point; PointValue() { } PointValue(PointValue c) { value = c.value; point = c.point; } PointValue(int p, double v) { value = v; point = p; } boolean equal(PointValue compare) { if (compare == null) return false; else return (compare.point == point); } } /** * constructor MinMaxExtractorSynapse. */ public MinMaxExtractorPlugIn() { super(); } /** * Executes the extraction of the inversion points * (29/09/00 15.12.32) * @param serie int */ protected boolean convert(int serie) { boolean retValue = false; int pf = 0; double[] values; boolean up; PointValue lastInserted = null; PointValue lastInserting; java.util.Vector changePoints = new java.util.Vector(); PointValue pMax = new PointValue(0, getValuePoint(0, serie)); PointValue pMin = new PointValue(0, getValuePoint(0, serie)); PointValue pCur = new PointValue(); int s = getInputVector().size(); if (s > 1) { // Init if (getValuePoint(1, serie) > pMax.value) up = true; else up = false; } else return false; while (pf < (s - 1)) { if (up) { pCur.point = pf; pCur.value = getValuePoint(pf, serie); pf = findMax(pCur, serie); if (!pMin.equal(lastInserted)) { if (minPerc(getValuePoint(pf, serie), pMin.value)) { // Il pMin points to a valid relative min lastInserting = new PointValue(pMin.point, MIN_VALUE); changePoints.addElement(lastInserting); writeMidPoints(lastInserted, lastInserting, serie); retValue = true; lastInserted = new PointValue(lastInserting); // The found turning point becomes a possible pMax pMax.point = pf; pMax.value = getValuePoint(pf, serie); } } if (pMax.value < getValuePoint(pf, serie)) { pMax.point = pf; pMax.value = getValuePoint(pf, serie); } } up = false; pCur.point = pf; pCur.value = getValuePoint(pf, serie); pf = findMin(pCur, serie); if (!pMax.equal(lastInserted)) { if (minPerc(getValuePoint(pf, serie), pMax.value)) { // pMax points to a valid relative max lastInserting = new PointValue(pMax.point, MAX_VALUE); changePoints.addElement(lastInserting); writeMidPoints(lastInserted, lastInserting, serie); retValue = true; lastInserted = new PointValue(lastInserting); // il punto di inversione trovato diventa un pMin presunto pMin.point = pf; pMin.value = getValuePoint(pf, serie); } } if (pMin.value > getValuePoint(pf, serie)) { pMin.point = pf; pMin.value = getValuePoint(pf, serie); } up = true; } // Converts the values on the last line Pattern currPE; if (lastInserted.point < (s - 1)) { writeMidPoints(lastInserted, new PointValue(s - 1, MID_VALUE), serie); currPE = (Pattern) getInputVector().elementAt(s - 1); currPE.setValue(serie, MID_VALUE); retValue = true; } else { currPE = (Pattern) getInputVector().elementAt(s - 1); currPE.setValue(serie, lastInserted.value); retValue = true; } return retValue; } /** * Find the next down-turning point starting from the pInit.point * Returns the next point having the max value * /\ --> return * / \ * / * pInit -->/ * Data di creazione: (29/09/00 15.50.35) */ private int findMax(PointValue pInit, int serie) { int i = pInit.point + 1; int s = getInputVector().size(); double lastValue = pInit.value; while (i < s) { if (getValuePoint(i, serie) >= lastValue) { lastValue = getValuePoint(i, serie); ++i; } else break; } return --i; } /** * Find the next up-turning point starting from the pInit.point * Returns the next point having the min value * pInit --> \ * \ * \ / * \/ --> return * (29/09/00 15.50.35) */ private int findMin(PointValue pInit, int serie) { int i = pInit.point + 1; int s = getInputVector().size(); double lastValue = pInit.value; while (i < s) { if (getValuePoint(i, serie) <= lastValue) { lastValue = getValuePoint(i, serie); ++i; } else break; } return --i; } /** * Get the min percentage of change accepted to consider * a point as a turning point * (29/09/00 18.46.53) * @return double */ public double getMinChangePercentage() { return minPerc; } /** * Return TRUE if the percentage of change from first to last points is * greater than minPerc * (29/09/00 18.48.20) * @return boolean * @param last double * @param first double */ private boolean minPerc(double last, double first) { double perc = (last - first) / first; if (perc < 0.0) perc = perc * -1; if (perc < minPerc) return false; else return true; } /** * Set the min percentage of change accepted to consider * a point as a turning point * (29/09/00 18.46.53) * @param newMinPerc double */ public void setMinChangePercentage(double newMinPerc) { if ( minPerc != newMinPerc ) { minPerc = newMinPerc; super.fireDataChanged(); } } /** * Fill all the points from pointA to pointB calculating the intermediate values * (01/10/2000 19.18.11) */ private void writeMidPoints(PointValue pointA, PointValue pointB, int serie) { int i; double vi; double vmin, vmax, vdif; double rmin, rmax, rdif; Pattern currPE; if (pointA == null) { i = 0; vi = MID_VALUE; } else { i = pointA.point; vi = pointA.value; } if (vi < pointB.value) { rmin = vi; rmax = pointB.value; } else { rmax = vi; rmin = pointB.value; } if (getValuePoint(i, serie) < getValuePoint(pointB.point, serie)) { vmin = getValuePoint(i, serie); vmax = getValuePoint(pointB.point, serie); } else { vmax = getValuePoint(i, serie); vmin = getValuePoint(pointB.point, serie); } rdif = rmax - rmin; vdif = vmax - vmin; while (i < pointB.point) { vi = (getValuePoint(i, serie) - vmin) / vdif; vi = vi * rdif + rmin; currPE = (Pattern) getInputVector().elementAt(i); currPE.setValue(serie, vi); ++i; } } }
Java
package org.joone.util; import org.joone.log.*; import org.joone.engine.Layer; import org.joone.net.NeuralNet; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; /** * A SnapshotRecorder serves to create and record snapshots of a neural network * in a file as a serie of serialized objects graphs. A new clone of the * network is generated for each snapshot and only the core part (between the * input-layer and the output-layer) is kept. * * @author Olivier Hussenet */ public class SnapshotRecorder extends SnapshotPlugin implements java.io.Serializable { private static final long serialVersionUID = -8151866025667526018L; private static final ILogger log = LoggerFactory.getLogger (SnapshotRecorder.class); /** The Joone snapshot format (NeuralNet serialized objects graph) */ public static final String JOONE_FORMAT = "joone"; /** The VisAD snapshot format (NeuralNetData serialized objects graph). Not yet implemented */ public static final String VISAD_FORMAT = "visad"; private transient OutputStream os = null; private transient ObjectOutputStream oos = null; private String filename = ""; private String format = JOONE_FORMAT; /** * Creates the output stream used to write snapshots. * * @param net the current neural network */ protected void doStart () { try { os = new FileOutputStream(filename); oos = new ObjectOutputStream(os); } catch (IOException e) { log.warn ("IOException while opening OutputStream. Message is : " + e.getMessage (), e); } } /** * Generates a snapshot of the current state of the network, * * @param net the current neural network */ protected void doSnapshot () { if (oos != null) { if (JOONE_FORMAT.equals (format)) jooneSnapshot (getNeuralNet()); //else if (VISAD_FORMAT.equals (format)) // visadSnapshot (net); else jooneSnapshot (getNeuralNet()); } } /** * Generates a joone snapshot of the current state of the network, * * @param net the current neural network */ private void jooneSnapshot (NeuralNet net) { // Write a clone of the core part of // the NeuralNet to the output-stream try { // Clone the neural-net NeuralNet clone = net.cloneNet (); // Detach inputs Layer layer = clone.getInputLayer (); if (layer != null) layer.removeAllInputs (); // Detach outputs layer = clone.getOutputLayer (); if (layer != null) layer.removeAllOutputs (); // Write the clone oos.writeObject (clone); } catch (IOException e) { log.warn ("IOException while writing to OutputStream. Message is : " + e.getMessage (), e); } } /** * Flush the output buffer and close the file. * * @param net the current neural network */ protected void doStop () { try { if (oos != null) { oos.flush (); os.close (); } } catch (IOException e) { log.warn ("IOException while closing OutputStream. Message is : " + e.getMessage (), e); } } /** * Set the name of the file to which snapshots will be written. * * @param name the new snapshots file name. */ public void setFilename (String name) { filename = name; } /** * Get the name of the file to which snapshots will be written. * * @return the current snapshots file name. */ public String getFilename () { return filename; } /** * Get the format used for snapshots. * * @return the current snapshots format */ public String getFormat () { return format; } /** * Set the format used for snapshots. * Legal values are: 'visad' or 'java'. * * @param format the new snapshots format */ public void setFormat (String format) { this.format = format; } protected void manageStopError(org.joone.engine.Monitor mon, String msgErr) { } }
Java
package org.joone.samples.engine.parity; import java.util.Vector; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.engine.listeners.*; import org.joone.io.*; import org.joone.log.*; import org.joone.net.*; import org.joone.structure.Nakayama; /** * Sample class to show the working of the technique for optimizing activation * functions. * * @author Boris Jansen */ public class Parity_Structure_Nakayama implements NeuralNetListener, java.io.Serializable { /** Logger for this class. */ private static final ILogger log = LoggerFactory.getLogger(Nakayama.class); private NeuralNet nnet = null; private MemoryInputSynapse inputSynapse, desiredOutputSynapse; private MemoryOutputSynapse outputSynapse; /** Optimizer. */ private Nakayama nakayama; // Parity input private double[][] inputArray = new double[][] { {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 1.0}, {0.0, 0.0, 1.0, 0.0}, {0.0, 0.0, 1.0, 1.0}, {0.0, 1.0, 0.0, 0.0}, {0.0, 1.0, 0.0, 1.0}, {0.0, 1.0, 1.0, 0.0}, {0.0, 1.0, 1.0, 1.0}, {1.0, 0.0, 0.0, 0.0}, {1.0, 0.0, 0.0, 1.0}, {1.0, 0.0, 1.0, 0.0}, {1.0, 0.0, 1.0, 1.0}, {1.0, 1.0, 0.0, 0.0}, {1.0, 1.0, 0.0, 1.0}, {1.0, 1.0, 1.0, 0.0}, {1.0, 1.0, 1.0, 1.0} }; // Parity desired output private double[][] desiredOutputArray = new double[][] { {0.0}, {1.0}, {1.0}, {0.0}, {1.0}, {0.0}, {0.0}, {1.0}, {1.0}, {0.0}, {0.0}, {1.0}, {0.0}, {1.0}, {1.0}, {0.0} }; /** * @param args the command line arguments */ public static void main(String args[]) { Parity_Structure_Nakayama parity = new Parity_Structure_Nakayama(); parity.initNeuralNet(); parity.train(); } /** * Method declaration */ public void train() { // set the inputs inputSynapse.setInputArray(inputArray); inputSynapse.setAdvancedColumnSelector("1-4"); // set the desired outputs desiredOutputSynapse.setInputArray(desiredOutputArray); desiredOutputSynapse.setAdvancedColumnSelector("1"); // get the monitor object to train or feed forward Monitor monitor = nnet.getMonitor(); // set the monitor parameters monitor.setUseRMSE(false); monitor.setLearningRate(0.5); monitor.setMomentum(0.3); monitor.setTrainingPatterns(inputArray.length); monitor.setTotCicles(5000); monitor.setLearning(true); // RPROP parameters monitor.addLearner(0, "org.joone.engine.RpropLearner"); monitor.addLearner(1, "org.joone.engine.BatchLearner"); monitor.addLearner(2, "org.joone.engine.BasicLearner"); monitor.setBatchSize(inputArray.length); monitor.setLearningMode(2); // Nakayama networks work only in multi-thread mode monitor.setSingleThreadMode(false); nnet.addNeuralNetListener(this); nnet.go(); } private void test() { nnet.getMonitor().setTotCicles(1); nnet.getMonitor().setLearning(false); // Nakayama networks work only in multi-thread mode nnet.getMonitor().setSingleThreadMode(false); // Enables the MemoryOutputSynapse in order to get the results of the network outputSynapse.setEnabled(true); nnet.removeAllListeners(); nnet.go(true); Vector patts = outputSynapse.getAllPatterns(); System.out.println("\nResults:"); for(int i = patts.size(); i > 0; i--) { Pattern pattern = (Pattern)patts.elementAt(patts.size() - i); System.out.println("Output Pattern #"+(patts.size() - i)+" = " + pattern.getArray()[0]); } System.out.println("Final RMSE: " + nnet.getMonitor().getGlobalError()); } /** * Method declaration */ protected void initNeuralNet() { // First create the three layers LinearLayer input = new LinearLayer(); SigmoidLayer hiddenSigmoid = new SigmoidLayer(); SineLayer hiddenSine = new SineLayer(); GaussLayer hiddenGauss = new GaussLayer(); SigmoidLayer output = new SigmoidLayer(); // set the dimensions of the layers input.setRows(4); hiddenSigmoid.setRows(8); hiddenSine.setRows(8); hiddenGauss.setRows(8); output.setRows(1); // Now create the synapses FullSynapse synapse_IHSIGMOID = new FullSynapse(); FullSynapse synapse_IHSINE = new FullSynapse(); FullSynapse synapse_IHGAUSS = new FullSynapse(); FullSynapse synapse_HSIGMOIDO = new FullSynapse(); FullSynapse synapse_HSINEO = new FullSynapse(); FullSynapse synapse_HGAUSSO = new FullSynapse(); input.addOutputSynapse(synapse_IHSIGMOID); input.addOutputSynapse(synapse_IHSINE); input.addOutputSynapse(synapse_IHGAUSS); hiddenSigmoid.addInputSynapse(synapse_IHSIGMOID); hiddenSine.addInputSynapse(synapse_IHSINE); hiddenGauss.addInputSynapse(synapse_IHGAUSS); hiddenSigmoid.addOutputSynapse(synapse_HSIGMOIDO); hiddenSine.addOutputSynapse(synapse_HSINEO); hiddenGauss.addOutputSynapse(synapse_HGAUSSO); output.addInputSynapse(synapse_HSIGMOIDO); output.addInputSynapse(synapse_HSINEO); output.addInputSynapse(synapse_HGAUSSO); // the input to the neural net inputSynapse = new MemoryInputSynapse(); input.addInputSynapse(inputSynapse); // the output of the neural net outputSynapse = new MemoryOutputSynapse(); output.addOutputSynapse(outputSynapse); // NEVER use an enabled xxxOutputSynapse when in training mode outputSynapse.setEnabled(false); // The Trainer and its desired output desiredOutputSynapse = new MemoryInputSynapse(); TeachingSynapse trainer = new TeachingSynapse(); trainer.setDesired(desiredOutputSynapse); // Now we add this structure to a NeuralNet object nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hiddenSigmoid, NeuralNet.HIDDEN_LAYER); nnet.addLayer(hiddenSine, NeuralNet.HIDDEN_LAYER); nnet.addLayer(hiddenGauss, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); output.addOutputSynapse(trainer); nakayama = new Nakayama(nnet); nakayama.addLayer(hiddenSigmoid); nakayama.addLayer(hiddenSine); nakayama.addLayer(hiddenGauss); // ErrorBasedConvergenceObserver myObserver = new ErrorBasedConvergenceObserver(); // myObserver.setPercentage(0.01); // myObserver.addConvergenceListener(nakayama); // nnet.addNeuralNetListener(myObserver); DeltaBasedConvergenceObserver myObserver = new DeltaBasedConvergenceObserver(); myObserver.setSize(0.0005); myObserver.setNeuralNet(nnet); myObserver.addConvergenceListener(nakayama); nnet.addNeuralNetListener(myObserver); } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); int c = mon.getTotCicles()-mon.getCurrentCicle(); if ((c % 100) == 0) { System.out.println("Cycle: "+c+" (R)MSE:"+mon.getGlobalError()); } // if(mon.getCurrentCicle() == 5000 || mon.getCurrentCicle() == 1000) { // nakayama.optimize(); // } } public void netStarted(NeuralNetEvent e) { } public void netStopped(NeuralNetEvent e) { test(); } public void netStoppedError(NeuralNetEvent e, String error) { } }
Java
/* * Validation_using_stream.java * * Created on January 18, 2006, 5:30 PM * */ package org.joone.samples.engine.helpers; import java.io.File; import org.joone.engine.Monitor; import org.joone.engine.NeuralNetListener; import org.joone.helpers.factory.JooneTools; import org.joone.io.FileInputSynapse; import org.joone.net.NeuralNet; import org.joone.net.NeuralNetAttributes; import org.joone.util.NormalizerPlugIn; /** * Example to demonstrate how to use the helpers methods of the JooneTools class * with a StreamInputSynapse used as data source. * @author P.Marrone */ public class Validation_using_stream implements NeuralNetListener { private static final String fileName = "org/joone/samples/engine/helpers/wine.txt"; private static final int trainingRows = 150; private double[][] inputTrain; private double[][] desiredTrain; private double[][] inputTest; private double[][] desiredTest; /** * Creates a new instance of Validation_using_stream */ public Validation_using_stream() { } /** * @param args the command line arguments */ public static void main(String[] args) { Validation_using_stream me = new Validation_using_stream(); me.go(); } private void go() { // Prepare the training and testing data set FileInputSynapse fileIn = new FileInputSynapse(); fileIn.setInputFile(new File(fileName)); fileIn.setAdvancedColumnSelector("1-14"); // Input data normalized between -1 and 1 NormalizerPlugIn normIn = new NormalizerPlugIn(); normIn.setAdvancedSerieSelector("2-14"); normIn.setMin(-1); normIn.setMax(1); fileIn.addPlugIn(normIn); // Target data normalized between 0 and 1 NormalizerPlugIn normOut = new NormalizerPlugIn(); normOut.setAdvancedSerieSelector("1"); fileIn.addPlugIn(normOut); // Extract the training data inputTrain = JooneTools.getDataFromStream(fileIn, 1, trainingRows, 2, 14); desiredTrain = JooneTools.getDataFromStream(fileIn, 1, trainingRows, 1, 1); // Extract the test data inputTest = JooneTools.getDataFromStream(fileIn, trainingRows+1, 178, 2, 14); desiredTest = JooneTools.getDataFromStream(fileIn, trainingRows+1, 178, 1, 1); int[] nodes = { 13, 4, 1 }; NeuralNet nnet = JooneTools.create_standard(nodes, JooneTools.LOGISTIC); // Set optimal values for learning rate and momentum nnet.getMonitor().setLearningRate(0.3); nnet.getMonitor().setMomentum(0.5); // nnet.getMonitor().setSingleThreadMode(false); // Trains the network JooneTools.train(nnet, inputTrain, desiredTrain, 5000, // Max # of epochs 0.010, // Stop RMSE 100, // Epochs between output reports this, // The listener false); // Runs in synch mode // Gets and prints the final values NeuralNetAttributes attrib = nnet.getDescriptor(); System.out.println("Last training rmse="+attrib.getTrainingError()+ " at epoch "+attrib.getLastEpoch()); double[][] out = JooneTools.compare(nnet, inputTest, desiredTest); System.out.println("Comparion of the last "+out.length+" rows:"); int cols = out[0].length/2; for (int i=0; i < out.length; ++i) { System.out.print("\nOutput: "); for (int x=0; x < cols; ++x) { System.out.print(out[i][x]+" "); } System.out.print("\tTarget: "); for (int x=cols; x < cols*2; ++x) { System.out.print(out[i][x]+" "); } } } public void cicleTerminated(org.joone.engine.NeuralNetEvent e) { // Gets the current values Monitor mon = (Monitor)e.getSource(); int epoch = mon.getTotCicles() - mon.getCurrentCicle() + 1; double trainErr = mon.getGlobalError(); // Test a clone of the network NeuralNet n = e.getNeuralNet().cloneNet(); double testErr = JooneTools.test(n, inputTest, desiredTest); System.out.println("Epoch "+epoch+":\n\tTraining error="+trainErr+"\n\tValidation error="+testErr); } public void errorChanged(org.joone.engine.NeuralNetEvent e) { } public void netStarted(org.joone.engine.NeuralNetEvent e) { System.out.println("Training..."); } public void netStopped(org.joone.engine.NeuralNetEvent e) { System.out.println("Training stopped."); } public void netStoppedError(org.joone.engine.NeuralNetEvent e, String error) { System.out.println("Training stopped with error "+error); } }
Java
/* * XOR_using_helpers.java * * Created on January 17, 2006, 5:21 PM * * Copyright @2005 by Paolo Marrone and the Joone team * Licensed under the Lesser General Public License (LGPL); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.gnu.org/ * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joone.samples.engine.helpers; import org.joone.helpers.factory.JooneTools; import org.joone.net.NeuralNet; /** * Example to demonstrate the use of the helpers classes * @author P.Marrone */ public class XOR_using_helpers { // XOR input private static double[][] inputArray = new double[][] { {0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 1.0} }; // XOR desired output private static double[][] desiredArray = new double[][] { {0.0}, {1.0}, {1.0}, {0.0} }; private static boolean singleThreadMode = true; /** * Creates a new instance of XOR_using_helpers */ public XOR_using_helpers() { } public static void main(String[] args) { try { // Create the network: 3 layers with a logistic output layer NeuralNet nnet = JooneTools.create_standard(new int[]{ 2, 2, 1 }, JooneTools.LOGISTIC); // NeuralNet nnet = JooneTools.load("org/joone/samples/engine/helpers/rxor.snet"); nnet.getMonitor().setSingleThreadMode(singleThreadMode); // Train the network for 5000 epochs, or until rmse reaches 0.01. // Outputs the results every 200 epochs on the stardard output double rmse = JooneTools.train(nnet, inputArray, desiredArray, 5000, 0.01, 200, System.out, false); // Waits in order to avoid the interlacing of the rows displayed try { Thread.sleep(50); } catch (InterruptedException doNothing) { } // Interrogate the network and prints the results System.out.println("Last RMSE = "+rmse); System.out.println("\nResults:"); System.out.println("|Inp 1\t|Inp 2\t|Output"); for (int i=0; i < 4; ++i) { double[] output = JooneTools.interrogate(nnet, inputArray[i]); System.out.print("| "+inputArray[i][0]+"\t| "+inputArray[i][1]+"\t| "); System.out.println(output[0]); } // Test the network and prints the rmse double testRMSE = JooneTools.test(nnet, inputArray, desiredArray); System.out.println("\nTest error = "+testRMSE); } catch (Exception exc) { exc.printStackTrace(); } } }
Java
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ /* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net * * XORMemory.java * */ package org.joone.samples.engine.xpath; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.*; import java.util.Vector; //import groovy.lang.*; /** * Sample class to demostrate the use of the MemoryInputSynapse * * @author Jos�?Rodriguez */ public class XOR_using_NeuralNet implements NeuralNetListener { private NeuralNet nnet = null; private MemoryInputSynapse inputSynapse, desiredOutputSynapse; private MemoryOutputSynapse outputSynapse; // XOR input private double[][] inputArray = new double[][] { {0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 1.0} }; // XOR desired output private double[][] desiredOutputArray = new double[][] { {0.0}, {1.0}, {1.0}, {0.0} }; /** * @param args the command line arguments */ public static void main(String args[]) { XOR_using_NeuralNet xor = new XOR_using_NeuralNet(); xor.initNeuralNet(); // call groovy expressions from Java code //xor.train(); } /** * Method declaration */ public void train() { // set the inputs inputSynapse.setInputArray(inputArray); inputSynapse.setAdvancedColumnSelector("1,2"); // set the desired outputs desiredOutputSynapse.setInputArray(desiredOutputArray); desiredOutputSynapse.setAdvancedColumnSelector("1"); // get the monitor object to train or feed forward Monitor monitor = nnet.getMonitor(); // set the monitor parameters monitor.setLearningRate(0.8); monitor.setMomentum(0.3); monitor.setTrainingPatterns(inputArray.length); monitor.setTotCicles(1000); monitor.setLearning(true); nnet.addNeuralNetListener(this); // nnet.start(); // nnet.getMonitor().Go(); // nnet.join(); // System.out.println("Network stopped. Last RMSE="+nnet.getMonitor().getGlobalError()); } /** * Method declaration */ protected void initNeuralNet() { // First create the three layers LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); input.setLayerName("input"); hidden.setLayerName("hidden"); output.setLayerName("output"); // set the dimensions of the layers input.setRows(2); hidden.setRows(3); output.setRows(1); // Now create the two Synapses FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); // the input to the neural net inputSynapse = new MemoryInputSynapse(); input.addInputSynapse(inputSynapse); // the output of the neural net outputSynapse = new MemoryOutputSynapse(); output.addOutputSynapse(outputSynapse); // The Trainer and its desired output desiredOutputSynapse = new MemoryInputSynapse(); TeachingSynapse trainer = new TeachingSynapse(); trainer.setDesired(desiredOutputSynapse); // Now we add this structure to a NeuralNet object nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); output.addOutputSynapse(trainer); train(); // try { // // Groovy // Binding binding = new Binding(); // binding.setVariable("network", nnet); // GroovyShell shell = new GroovyShell(binding); // // Object value = // shell.evaluate("network.layers.allOutputs.findAll{it.class.name=='org.joone.engine.learning.TeachingSynapse'}.desired.advancedColumnSelector"); // System.out.println("result="+value.toString()+" "+value.getClass().getName()); // } catch (Exception e) { e.printStackTrace(); } } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); System.out.println("Cycle: "+(mon.getTotCicles()-mon.getCurrentCicle())+" RMSE:"+mon.getGlobalError()); } public void netStarted(NeuralNetEvent e) { } public void netStopped(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); // Read the last pattern and print it out Vector patts = outputSynapse.getAllPatterns(); Pattern pattern = (Pattern)patts.elementAt(patts.size() - 1); System.out.println("Output Pattern = " + pattern.getArray()[0]); } public void netStoppedError(NeuralNetEvent e, String error) { } } /*--- formatting done in "JMRA based on Sun Java Convention" style on 05-25-2002 ---*/
Java
/* * TimeSeriesForecasting.java * * Created on 10 giugno 2005, 21.31 */ package org.joone.samples.engine.timeseries; import java.io.File; import org.joone.engine.DelayLayer; import org.joone.engine.FullSynapse; import org.joone.engine.Layer; import org.joone.engine.Monitor; import org.joone.engine.NeuralNetListener; import org.joone.engine.SigmoidLayer; import org.joone.engine.Synapse; import org.joone.engine.TanhLayer; import org.joone.engine.learning.TeachingSynapse; import org.joone.io.FileInputSynapse; import org.joone.io.FileOutputSynapse; import org.joone.net.NeuralNet; /** * * @author paolo */ public class TimeSeriesForecasting implements NeuralNetListener { static String path = "org/joone/samples/engine/timeseries/"; static String fileName = path+"timeseries.txt"; int trainingPatterns = 300; int epochs = 1000; int temporalWindow = 10; DelayLayer input; SigmoidLayer hidden; TanhLayer output; TeachingSynapse trainer; NeuralNet nnet; /** Creates a new instance of TimeSeriesForecasting */ public TimeSeriesForecasting() { } /** * @param args the command line arguments */ public static void main(String[] args) { TimeSeriesForecasting me = new TimeSeriesForecasting(); me.createNet(); System.out.println("Training..."); me.train(); me.interrogate(path+"results1.txt"); me.interrogate(path+"results2.txt"); System.out.println("Done."); } private void createNet() { input = new DelayLayer(); hidden = new SigmoidLayer(); output = new TanhLayer(); input.setTaps(temporalWindow-1); input.setRows(1); hidden.setRows(15); output.setRows(1); connect(input, new FullSynapse(), hidden); connect(hidden, new FullSynapse(), output); input.addInputSynapse(createDataSet(fileName, 1, trainingPatterns, "1")); trainer = new TeachingSynapse(); trainer.setDesired(createDataSet(fileName, 2, trainingPatterns+1, "1")); output.addOutputSynapse(trainer); nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); } private void train() { Monitor mon = nnet.getMonitor(); mon.setLearningRate(0.2); mon.setMomentum(0.7); mon.setTrainingPatterns(trainingPatterns); mon.setTotCicles(epochs); mon.setPreLearning(temporalWindow); mon.setLearning(true); mon.addNeuralNetListener(this); nnet.start(); mon.Go(); nnet.join(); } private void interrogate(String outputFile) { Monitor mon = nnet.getMonitor(); input.removeAllInputs(); int startRow = trainingPatterns - temporalWindow; input.addInputSynapse(createDataSet(fileName, startRow+1, startRow+20, "1")); output.removeAllOutputs(); FileOutputSynapse fOutput = new FileOutputSynapse(); fOutput.setFileName(outputFile); output.addOutputSynapse(fOutput); mon.setTrainingPatterns(20); mon.setTotCicles(1); mon.setLearning(false); nnet.start(); mon.Go(); nnet.join(); } private void connect(Layer layer1, Synapse syn, Layer layer2) { layer1.addOutputSynapse(syn); layer2.addInputSynapse(syn); } private FileInputSynapse createDataSet(String fileName, int firstRow, int lastRow, String advColSel) { FileInputSynapse fInput = new FileInputSynapse(); fInput.setInputFile(new File(fileName)); fInput.setFirstRow(firstRow); fInput.setLastRow(lastRow); fInput.setAdvancedColumnSelector(advColSel); return fInput; } public void cicleTerminated(org.joone.engine.NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); int epoch = mon.getTotCicles() - mon.getCurrentCicle(); if ((epoch > 0) && ((epoch % 100) == 0)) { System.out.println("Epoch:"+epoch+" RMSE="+mon.getGlobalError()); } } public void errorChanged(org.joone.engine.NeuralNetEvent e) { } public void netStarted(org.joone.engine.NeuralNetEvent e) { } public void netStopped(org.joone.engine.NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); if (mon.isLearning()) { int epoch = mon.getTotCicles() - mon.getCurrentCicle(); System.out.println("Epoch:"+epoch+" last RMSE="+mon.getGlobalError()); } } public void netStoppedError(org.joone.engine.NeuralNetEvent e, String error) { } }
Java
/* * TestXML.java * * Created on 28 aprile 2004, 22.17 */ package org.joone.samples.engine.xml; import org.joone.net.*; import org.joone.engine.*; import org.joone.io.*; import java.io.*; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; /** * * @author paolo */ public class TestXML implements NeuralNetListener, NeuralValidationListener { NeuralNet result; /** Creates a new instance of TestXML */ public TestXML() { } /** * @param args the command line arguments */ public static void main(String[] args) { new TestXML().elaborate(); } private void elaborate() { try { XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library // result = (NeuralNet)xstream.fromXML(new FileReader("/home/paolo/SourceForge/ValidationSample.xml")); result = (NeuralNet)xstream.fromXML(new FileReader("/home/paolo/SourceForge/xor.xml")); System.out.println("Unmarshaling Done"); result.getMonitor().addNeuralNetListener(this); result.getMonitor().setTotCicles(3000); result.randomize(0.2); result.start(); result.getMonitor().Go(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); if ((mon.getCurrentCicle() % 200) == 0) { System.out.println("RMSE at epoch "+(mon.getTotCicles()-mon.getCurrentCicle())+": "+mon.getGlobalError()); if (mon.getValidationPatterns() > 0) { NeuralNet newNet = result.cloneNet(); newNet.removeAllListeners(); NeuralNetValidator val = new NeuralNetValidator(newNet); val.addValidationListener(this); val.start(); } } } public void netStarted(NeuralNetEvent e) { System.out.println("Running..."); } public void netStopped(NeuralNetEvent e) { System.out.println("Finished"); } public void netStoppedError(NeuralNetEvent e, String error) { } public void netValidated(NeuralValidationEvent e) { // Shows the RMSE at the end of the cycle NeuralNet NN = (NeuralNet)e.getSource(); System.out.println("\tValidation error="+NN.getMonitor().getGlobalError()); } }
Java
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ /* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net * */ package org.joone.samples.engine.multipleInputs; import java.io.File; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.*; /** * Sample class to demostrate the use of the MultipleInputSynapse * * */ public class XOR_multipleInputs implements NeuralNetListener { private NeuralNet nnet = null; private FileInputSynapse inputSynapse1, inputSynapse2, inputSynapse3; private FileInputSynapse desiredSynapse1, desiredSynapse2, desiredSynapse3; // private MemoryOutputSynapse outputSynapse; private InputSwitchSynapse inputSw, desiredSw; private static String inputFileName = "org/joone/samples/engine/multipleInputs/xor.txt"; /** * @param args the command line arguments */ public static void main(String args[]) { XOR_multipleInputs xor = new XOR_multipleInputs(); xor.initNeuralNet(); xor.train(); xor.interrogate(); } /** * Method declaration */ public void train() { // get the monitor object to train or feed forward Monitor monitor = nnet.getMonitor(); // set the monitor parameters monitor.setLearningRate(0.8); monitor.setMomentum(0.3); monitor.setTrainingPatterns(9); monitor.setTotCicles(2000); monitor.setLearning(true); nnet.addNeuralNetListener(this); nnet.go(true); System.out.println("Network stopped. Last RMSE="+nnet.getMonitor().getGlobalError()); } private void interrogate() { // neuralNet is an instance of NeuralNet Monitor monitor=nnet.getMonitor(); monitor.setTotCicles(1); monitor.setLearning(false); FileOutputSynapse output=new FileOutputSynapse(); // set the output synapse to write the output of the net output.setFileName("/tmp/xorOut.txt"); // inject the input and get the output if(nnet!=null) { nnet.addOutputSynapse(output); System.out.println(nnet.check()); nnet.go(true); } } /** * Method declaration */ protected void initNeuralNet() { // First create the three layers LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); // set the dimensions of the layers input.setRows(2); hidden.setRows(3); output.setRows(1); input.setLayerName("inputLayer"); hidden.setLayerName("hiddenLayer"); output.setLayerName("outputLayer"); // Now create the two Synapses FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); // the input to the neural net inputSynapse1 = new FileInputSynapse(); inputSynapse2 = new FileInputSynapse(); inputSynapse3 = new FileInputSynapse(); inputSynapse1.setInputFile(new File(inputFileName)); inputSynapse1.setName("input1"); inputSynapse1.setAdvancedColumnSelector("1-2"); inputSynapse1.setFirstRow(1); inputSynapse1.setLastRow(4); inputSynapse2.setInputFile(new File(inputFileName)); inputSynapse2.setName("input2"); inputSynapse2.setAdvancedColumnSelector("1-2"); inputSynapse2.setFirstRow(2); inputSynapse2.setLastRow(4); inputSynapse3.setInputFile(new File(inputFileName)); inputSynapse3.setName("input3"); inputSynapse3.setAdvancedColumnSelector("1-2"); inputSynapse3.setFirstRow(3); inputSynapse3.setLastRow(4); inputSw = new MultipleInputSynapse(); inputSw.addInputSynapse(inputSynapse1); inputSw.addInputSynapse(inputSynapse2); inputSw.addInputSynapse(inputSynapse3); input.addInputSynapse(inputSw); // The Trainer and its desired output desiredSynapse1 = new FileInputSynapse(); desiredSynapse2 = new FileInputSynapse(); desiredSynapse3 = new FileInputSynapse(); desiredSynapse1.setInputFile(new File(inputFileName)); desiredSynapse1.setName("desired1"); desiredSynapse1.setAdvancedColumnSelector("3"); desiredSynapse1.setFirstRow(1); desiredSynapse1.setLastRow(4); desiredSynapse2.setInputFile(new File(inputFileName)); desiredSynapse2.setName("desired2"); desiredSynapse2.setAdvancedColumnSelector("3"); desiredSynapse2.setFirstRow(2); desiredSynapse2.setLastRow(4); desiredSynapse3.setInputFile(new File(inputFileName)); desiredSynapse3.setName("desired3"); desiredSynapse3.setAdvancedColumnSelector("3"); desiredSynapse3.setFirstRow(3); desiredSynapse3.setLastRow(4); desiredSw = new MultipleInputSynapse(); desiredSw.addInputSynapse(desiredSynapse1); desiredSw.addInputSynapse(desiredSynapse2); desiredSw.addInputSynapse(desiredSynapse3); TeachingSynapse trainer = new TeachingSynapse(); trainer.setDesired(desiredSw); // Now we add this structure to a NeuralNet object nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); output.addOutputSynapse(trainer); } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); if (mon.getCurrentCicle() % 100 == 0) System.out.println("Epoch: "+(mon.getTotCicles()-mon.getCurrentCicle())+" RMSE:"+mon.getGlobalError()); } public void netStarted(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); if (mon.isLearning()) System.out.println("Training..."); } public void netStopped(NeuralNetEvent e) { System.out.println("Stopped"); } public void netStoppedError(NeuralNetEvent e, String error) { } } /*--- formatting done in "JMRA based on Sun Java Convention" style on 05-25-2002 ---*/
Java
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ /* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net * */ package org.joone.samples.engine.multipleInputs; import java.io.File; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.*; /** * Sample class to demostrate the use of the MultipleInputSynapse * * */ public class XOR_inputSwitch implements NeuralNetListener { private NeuralNet nnet = null; private FileInputSynapse inputSynapse1, inputSynapse2, inputSynapse3; private FileInputSynapse desiredSynapse1, desiredSynapse2, desiredSynapse3; // private MemoryOutputSynapse outputSynapse; private InputSwitchSynapse inputSw, desiredSw; private static String inputFile = "/tmp/xor.txt"; /** * @param args the command line arguments */ public static void main(String args[]) { XOR_inputSwitch xor = new XOR_inputSwitch(); xor.initNeuralNet(); xor.train(); } /** * Method declaration */ public void train() { // get the monitor object to train or feed forward Monitor monitor = nnet.getMonitor(); // set the monitor parameters monitor.setLearningRate(0.8); monitor.setMomentum(0.3); monitor.setTrainingPatterns(4); monitor.setTotCicles(1000); monitor.setLearning(true); nnet.addNeuralNetListener(this); // nnet.start(); // nnet.getMonitor().Go(); // nnet.join(); // System.out.println("Network stopped. Last RMSE="+nnet.getMonitor().getGlobalError()); interrogate(); interrogate(); interrogate(); } private void interrogate() { // neuralNet is an instance of NeuralNet Monitor monitor=nnet.getMonitor(); monitor.setTotCicles(1); monitor.setLearning(false); FileOutputSynapse output=new FileOutputSynapse(); // set the output synapse to write the output of the net output.setFileName("/tmp/xorOut.txt"); // inject the input and get the output if(nnet!=null) { nnet.addOutputSynapse(output); System.out.println(nnet.check()); nnet.start(); monitor.Go(); nnet.join(); } } /** * Method declaration */ protected void initNeuralNet() { // First create the three layers LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); // set the dimensions of the layers input.setRows(2); hidden.setRows(3); output.setRows(1); input.setLayerName("inputLayer"); hidden.setLayerName("hiddenLayer"); output.setLayerName("outputLayer"); // Now create the two Synapses FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); // the input to the neural net inputSynapse1 = new FileInputSynapse(); inputSynapse2 = new FileInputSynapse(); inputSynapse3 = new FileInputSynapse(); inputSynapse1.setInputFile(new File(inputFile)); inputSynapse1.setName("input1"); inputSynapse1.setAdvancedColumnSelector("1-2"); inputSynapse1.setFirstRow(1); inputSynapse1.setLastRow(4); inputSynapse2.setInputFile(new File(inputFile)); inputSynapse2.setName("input2"); inputSynapse2.setAdvancedColumnSelector("1-2"); inputSynapse2.setFirstRow(2); inputSynapse2.setLastRow(3); inputSynapse3.setInputFile(new File(inputFile)); inputSynapse3.setName("input3"); inputSynapse3.setAdvancedColumnSelector("1-2"); inputSynapse3.setFirstRow(4); inputSynapse3.setLastRow(4); inputSw = new InputSwitchSynapse(); inputSw.addInputSynapse(inputSynapse1); inputSw.addInputSynapse(inputSynapse2); inputSw.addInputSynapse(inputSynapse3); input.addInputSynapse(inputSw); // The Trainer and its desired output desiredSynapse1 = new FileInputSynapse(); desiredSynapse2 = new FileInputSynapse(); desiredSynapse3 = new FileInputSynapse(); desiredSynapse1.setInputFile(new File(inputFile)); desiredSynapse1.setName("desired1"); desiredSynapse1.setAdvancedColumnSelector("3"); desiredSynapse1.setFirstRow(1); desiredSynapse1.setLastRow(4); desiredSynapse2.setInputFile(new File(inputFile)); desiredSynapse2.setName("desired2"); desiredSynapse2.setAdvancedColumnSelector("3"); desiredSynapse2.setFirstRow(2); desiredSynapse2.setLastRow(3); desiredSynapse3.setInputFile(new File(inputFile)); desiredSynapse3.setName("desired3"); desiredSynapse3.setAdvancedColumnSelector("3"); desiredSynapse3.setFirstRow(4); desiredSynapse3.setLastRow(4); desiredSw = new InputSwitchSynapse(); desiredSw.addInputSynapse(desiredSynapse1); desiredSw.addInputSynapse(desiredSynapse2); desiredSw.addInputSynapse(desiredSynapse3); TeachingSynapse trainer = new TeachingSynapse(); trainer.setDesired(desiredSw); // Now we add this structure to a NeuralNet object nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); output.addOutputSynapse(trainer); } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); System.out.println("Cycle: "+(mon.getTotCicles()-mon.getCurrentCicle())+" RMSE:"+mon.getGlobalError()); } public void netStarted(NeuralNetEvent e) { System.out.println("Training..."); } public void netStopped(NeuralNetEvent e) { System.out.println("Stopped"); } public void netStoppedError(NeuralNetEvent e, String error) { } } /*--- formatting done in "JMRA based on Sun Java Convention" style on 05-25-2002 ---*/
Java
/* * NetTrainer.java * * Created on 13 ottobre 2003, 19.41 */ package org.joone.samples.engine.validation; import java.util.*; import org.joone.engine.*; import org.joone.net.*; /** * This class trains and validates a neural network passed as parameter * of the constructor and, when the validation phase is finished, it * notifies its listeners. * The neural network passes as parameter is cloned before to use it, * so the calling program can call many copies of this class to train * and validate several copies of the same neural network. * * @author pmarrone */ public class NeuralNetTrainer implements Runnable, NeuralNetListener, NeuralValidationListener { private Vector listeners; private NeuralNet nnet; private Thread myThread = null; public NeuralNetTrainer(NeuralNet nn) { listeners = new Vector(); nnet = cloneNet(nn); } public void addValidationListener(NeuralValidationListener newListener){ if (!listeners.contains(newListener)) listeners.addElement(newListener); } /** * Trains the neural network */ protected void train() { //System.out.println("Training..."); nnet.getMonitor().addNeuralNetListener(this); nnet.getMonitor().setLearning(true); nnet.getMonitor().setValidation(false); nnet.go(true); this.validate(); } /** * Validates the trained neural network */ protected void validate(){ //System.out.println("Valitading..."); // Set all the parameters for the validation NeuralNet newNet = cloneNet(nnet); NeuralNetValidator nnv = new NeuralNetValidator(newNet); nnv.addValidationListener(this); nnv.start(); // Validates the net } /** * Clones the neural network passed as parameter */ private NeuralNet cloneNet(NeuralNet net) { // Creates a copy of the neural network net.getMonitor().setExporting(true); NeuralNet newNet = net.cloneNet(); net.getMonitor().setExporting(false); // Cleans the old listeners // This is a fundamental action to avoid that the validated net // calls any method of previously registered listeners newNet.removeAllListeners(); return newNet; } // Notifies all the registered listeners private void fireNetValidated(NeuralValidationEvent event) { NeuralNet NN = (NeuralNet)event.getSource(); NN.terminate(false); // <-- Added as a bug workaround for (int i=0; i < listeners.size(); ++i) { NeuralValidationListener nvl = (NeuralValidationListener)listeners.elementAt(i); nvl.netValidated(new NeuralValidationEvent(NN)); } } /** Starts the training & validation phases into a separated thread */ public void start() { if (myThread == null) { myThread = new Thread(this, "Trainer"); myThread.start(); } } public void run() { this.train(); myThread = null; } public void netStopped(NeuralNetEvent e) { } public void netValidated(NeuralValidationEvent event) { // When also the validation phase terminates, then notifies all the listeners this.fireNetValidated(event); } public void cicleTerminated(NeuralNetEvent e) { //System.out.println("Cycle "+nnet.getMonitor().getCurrentCicle()+" terminated"); } public void netStarted(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { /*System.out.println("Error "+nnet.getMonitor().getCurrentCicle()+" changed"); System.out.println("Tot Cycles: "+nnet.getMonitor().getTotCicles()); System.out.println("Val. Patt.: "+nnet.getMonitor().getValidationPatterns()); System.out.println("Tr. Patt.: "+nnet.getMonitor().getTrainingPatterns()); */ } public void netStoppedError(NeuralNetEvent e, String error) { System.exit(1); } }
Java
package org.joone.samples.engine.validation; import java.util.*; import org.joone.engine.*; import org.joone.inspection.implementations.*; import org.joone.io.*; import org.joone.net.*; /* * <p>Title: Effort Estimations Through Neural Networks - Joone Test</p> * <p>Description: Stage II - Joone Pilot</p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: Motorola</p> * @author Sebastian Donatti - AGD013 * @version 1.0.0 */ public class NeuralNetTester implements Runnable,NeuralNetListener,NeuralValidationListener{ // Joone Global Variables private Vector listeners; private NeuralNet oldNetwork; private NeuralNet newNetwork; private Thread myThread=null; private double lastRSME; private int minimaEpochs; // JoonePilot Global Variables; private int problem; private boolean relaunch; private static int relaunchNumber; private boolean learnCurve; // Added to avoid to print all the intermediate errors when in learning curve mode // Launches the train & validation of one neural network - Class Constructor public NeuralNetTester(NeuralNet _network,boolean lCurve,int _problem){ problem=_problem; listeners=new Vector(); oldNetwork=_network; newNetwork=cloneNet(_network); learnCurve=lCurve; lastRSME=0; minimaEpochs=0; relaunch=false; } public void addValidationListener(NeuralValidationListener newListener){ if(!listeners.contains(newListener)){ listeners.addElement(newListener); } } // Trains the neural network - Class Method protected void train(){ newNetwork.getMonitor().addNeuralNetListener(this); newNetwork.getMonitor().setLearning(true); newNetwork.getMonitor().setValidation(false); newNetwork.start(); newNetwork.getMonitor().Go(); } // Validates the trained neural network - Class Method protected void validate(){ if(!learnCurve){ // Update Screen System.out.print("\nTraining Finished \n"); System.out.print("\nValidation Started\n\n"); } // Set all the parameters for the validation NeuralNetValidator nnv=new NeuralNetValidator(cloneNet(newNetwork)); nnv.addValidationListener(this); // Validate the network nnv.start(); } // Clones the neural network passed as parameter - Class Method private NeuralNet cloneNet(NeuralNet oldNet){ // Create a copy of the neural network oldNet.getMonitor().setExporting(true); NeuralNet newNet=oldNet.cloneNet(); oldNet.getMonitor().setExporting(false); // Clean the old listeners (This is a fundamental action to avoid that the validated net calls any method of previously registered listeners) newNet.removeAllListeners(); return newNet; } // Notifies all the registered listeners - Class Method private void fireNetValidated(NeuralValidationEvent event){ NeuralNet NN=(NeuralNet)event.getSource(); for(int i=0;i<listeners.size();++i){ NeuralValidationListener nvl=(NeuralValidationListener)listeners.elementAt(i); nvl.netValidated(new NeuralValidationEvent(NN)); } } // Starts the training & validation phases into a separated thread - Class Method public void start(){ if(myThread==null){ myThread=new Thread(this); myThread.start(); } } public void run(){ this.train(); myThread=null; } // Interface Method public void netStopped(NeuralNetEvent e){ // Learning Curve is not selected if(!learnCurve){ // Stopped in error if(relaunch){ // Relaunch the training relaunchNumber=relaunchNumber+1; relaunch=false; minimaEpochs=0; newNetwork=cloneNet(oldNetwork); // Shuffle the Input inputRandomize(); newNetwork.resetInput(); // Shuffle the network switch(problem){ case 1: newNetwork.randomize(0.7); break; case 2: newNetwork.randomize(0.5); break; case 3: newNetwork.randomize(0.5); break; } this.train(); System.out.print(" Training Relaunched: "+relaunchNumber+"\n\n"); } // Stopped Correctly else{ // Validate the network when the training phase terminates this.validate(); } } // Learning Curve is Selected else{ // Stopped in error if(relaunch){ // Relaunch the training relaunchNumber=relaunchNumber+1; System.out.print("Relaunch Number: "+relaunchNumber+"\n"); relaunch=false; minimaEpochs=0; newNetwork=cloneNet(oldNetwork); // Shuffle the Input inputRandomize(); newNetwork.resetInput(); // Shuffle the network switch(problem){ case 1: newNetwork.randomize(0.7); break; case 2: newNetwork.randomize(0.5); break; case 3: newNetwork.randomize(0.5); break; } this.train(); } // Stopped Correctly else{ // Validate the network when the training phase terminates this.validate(); } } } public void netValidated(NeuralValidationEvent event){ // Notify all the listeners when also the validation phase terminates this.fireNetValidated(event); if(!learnCurve){ // Update Screen System.out.print("\nValidation Finished\n"); } } public void cicleTerminated(NeuralNetEvent e){ if(!learnCurve){ // Declare & Initialize the local variables double currentError=newNetwork.getMonitor().getGlobalError(); int currentCycle=newNetwork.getMonitor().getCurrentCicle(); int cycles=newNetwork.getMonitor().getTotCicles(); int printCycle=currentCycle/10; // Print the results every 1000 cycles if((printCycle*10)==currentCycle){ // Declare & Initialize the local variables int remaining=cycles-currentCycle; int percentage=(remaining*100)/cycles; // Update Screen System.out.print("RSME: "+currentError+"\n"); } } } public void netStarted(NeuralNetEvent e){ } public void errorChanged(NeuralNetEvent event){ Monitor monitor=(Monitor)event.getSource(); double rmse=monitor.getGlobalError(); // Stop the network if the Global RSME is lower than the Minimum Expected if(rmse<=0.05){ monitor.Stop(); } // Check if the network has become stuck in local minima else{ if(lastRSME<=(monitor.getGlobalError()+0.0000005)){ minimaEpochs=minimaEpochs+1; } else{ minimaEpochs=0; } } lastRSME=monitor.getGlobalError(); // Relaunches the training if has becomed stuck in a local minima if(minimaEpochs==3000){ // Stop the training in error if(!learnCurve){ System.out.print("\n\n Training Patterns: "+monitor.getTrainingPatterns()+" - LOCAL MINIMA STUCK \n"); } relaunch=true; monitor.Stop(); } } /** Randomizes the Network Input Vector - Class Method */ private void inputRandomize(){ // Get the input Synapse boolean notNullFlag=false; Layer inputLayer=newNetwork.getInputLayer(); Vector inputList=inputLayer.getAllInputs(); StreamInputSynapse inputSynapse; inputSynapse=null; // Get the Switch for(int i=0;i<inputList.size();i++){ InputSwitchSynapse inputSwitchTemporal=(InputSwitchSynapse)inputList.elementAt(i); if(inputSwitchTemporal.getName().equals("Input Switch Synapse")){ Vector inputSwitch=inputSwitchTemporal.getAllInputs(); // Get the Synapse for(int j=0;j<inputSwitch.size();j++){ StreamInputSynapse inputSynapseTemporal=(StreamInputSynapse)inputSwitch.elementAt(i); if(inputSynapseTemporal.getName().equals("Learning Input Synapse")){ inputSynapse=inputSynapseTemporal; notNullFlag=true; } } } } // Get the array if the Synapse has been found if(notNullFlag){ Collection inputCollection; inputCollection=inputSynapse.Inspections(); Iterator temporalIterator=inputCollection.iterator(); InputsInspection temporalInspection=(InputsInspection)temporalIterator.next(); Object[][] inputElements=temporalInspection.getComponent(); // Create the random number Random joker=new Random(); int changerPatternNumberA=joker.nextInt(inputElements.length); int changedPatternNumberA=joker.nextInt(inputElements.length); int changerPatternNumberB=joker.nextInt(inputElements.length); int changedPatternNumberB=joker.nextInt(inputElements.length); // Shuffle the array order Object[] temporalPatternA=inputElements[changedPatternNumberA]; Object[] temporalPatternB=inputElements[changedPatternNumberB]; inputElements[changedPatternNumberA]=inputElements[changerPatternNumberA]; inputElements[changerPatternNumberA]=temporalPatternA; inputElements[changedPatternNumberB]=inputElements[changerPatternNumberB]; inputElements[changerPatternNumberB]=temporalPatternB; // Save the new array temporalInspection.setComponent(inputElements); inputRandomizeCheck(); } } /** Used to Check if the Network Input Vector is randomized - Class Method */ private void inputRandomizeCheck(){ // Get the input Synapse boolean notNullFlagCheck=false; Layer inputLayerCheck=newNetwork.getInputLayer(); Vector inputListCheck=inputLayerCheck.getAllInputs(); StreamInputSynapse inputSynapseCheck; inputSynapseCheck=null; // Get the Switch for(int i=0;i<inputListCheck.size();i++){ InputSwitchSynapse inputSwitchTemporalCheck=(InputSwitchSynapse)inputListCheck.elementAt(i); if(inputSwitchTemporalCheck.getName().equals("Input Switch Synapse")){ Vector inputSwitch=inputSwitchTemporalCheck.getAllInputs(); // Get the Synapse for(int j=0;j<inputSwitch.size();j++){ StreamInputSynapse inputSynapseTemporal=(StreamInputSynapse)inputSwitch.elementAt(i); if(inputSynapseTemporal.getName().equals("Learning Input Synapse")){ inputSynapseCheck=inputSynapseTemporal; notNullFlagCheck=true; } } } } // Get the array if the Synapse has been found if(notNullFlagCheck){ Collection inputCollectionCheck; inputCollectionCheck=inputSynapseCheck.Inspections(); Iterator temporalIteratorCheck=inputCollectionCheck.iterator(); InputsInspection temporalInspectionCheck=(InputsInspection)temporalIteratorCheck.next(); Object[][] inputElementsCheck=temporalInspectionCheck.getComponent(); int javaDebugStop =0; } } public void netStoppedError(NeuralNetEvent e,String error){ // Update the Screen System.out.print("Stopped in Error \n"); } }
Java
/* * ValidationSample.java * * Created on 11 november 2002, 22.59 * @author pmarrone */ package org.joone.samples.engine.validation; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.net.*; import org.joone.io.*; import org.joone.util.*; import java.io.*; /** * This example shows how to check the training level of a neural network * using a validation data source. * The training and the validation phases of the created network is executed * many times, showing for each one the resulting RMSE. * This program shows how to build the same kind of neural net as that * contained into the org/joone/samples/editor/scripting/ValidationSample.ser * file using only java code and the core engine's API. Open that net in * the GUI editor to see the architecture of the net built in this example. */ public class MultipleValidationSample implements NeuralValidationListener { NeuralNet nnet; boolean ready; int totNets = 10; // Number of neural nets to train & validate int returnedNets = 0; double totRMSE = 0; double minRMSE = 99; long mStart; int trainingLCP = 1; int validationLCP = 16; int totCycles = 1000; FileWriter wr = null; private static String filePath = "org/joone/samples/engine/validation"; // Must point to a trained XOR network without I/O components String xorNet = filePath+"/trainedXOR.snet"; /** Creates a new instance of SampleScript */ public MultipleValidationSample() { } /** * @param args the command line arguments */ public static void main(String[] args) { MultipleValidationSample sampleNet = new MultipleValidationSample(); sampleNet.start(); } private void start() { try{ wr = new FileWriter(new File("/tmp/memory.txt")); while (trainingLCP <= validationLCP){ // Start the LC Calculation startValidation(trainingLCP,validationLCP); trainingLCP += 1; wr.flush(); } // Draws the error's curve wr.close(); } catch (IOException ioe){ioe.printStackTrace();} System.out.println("Done."); System.exit(0); } private synchronized void startValidation(int trnP, int valP) { nnet = initializeModularParity(trnP, valP); //nnet = initializeSimpleParity(trnP, valP); //nnet = initializeNetworkI(trnP, valP); nnet.getMonitor().setTrainingPatterns(trnP); nnet.getMonitor().setValidationPatterns(valP); try { mStart = System.currentTimeMillis(); returnedNets = 0; totRMSE = 0; minRMSE = 99; // n = total number of neural networks to create, train and validate int n = totNets; // First of all, starts the initial number of // neural networks that must be trained in parallel for (int i=0; i < 1; ++i) { test(n--); } while (n > 0) { // Waits for a neural network's validation termination // before to start another one while (!ready) { try { wait(); } catch (InterruptedException doNothing) {} } ready = false; test(n--); long mem = getMemoryUse(); wr.write(mem+"\r\n"); } while (returnedNets < totNets){ try { wait(); } catch (InterruptedException doNothing) {} } // This code is executed when all the neural networks // have been trained and validated displayResults(); } catch (IOException ioe) { ioe.printStackTrace(); } } // Run a new training & validation phase private void test(int n) { nnet.randomize(0.5); nnet.setParam("ID", new Integer(n)); // Set its param ID // Create the trainer object NeuralNetTrainer trainer = new NeuralNetTrainer(nnet); //NeuralNetTester trainer = new NeuralNetTester(nnet,true,0); // Registers itself as a listener of the trainer object trainer.addValidationListener(this); // Run the training+validation tasks trainer.start(); } /* This method is called by the trainers for each validated neural network * The param ID is used to recognize the returned net */ public synchronized void netValidated(NeuralValidationEvent event) { // Shows the RMSE at the end of the validation phase NeuralNet NN = (NeuralNet)event.getSource(); int n = ((Integer)NN.getParam("ID")).intValue(); double rmse = NN.getMonitor().getGlobalError(); //System.out.print("Returned NeuralNet #"+n); //System.out.println(" Validation RMSE: "+rmse); totRMSE += rmse; if (minRMSE > rmse) minRMSE = rmse; ++returnedNets; ready = true; notifyAll(); } private void displayResults(){ // This code is executed when all the neural networks have been trained and validated double aveRMSE = totRMSE/totNets; long mTot = System.currentTimeMillis()-mStart; System.out.println("---------------------------------------------------------"); System.out.println("Training Patterns: "+trainingLCP); System.out.println("Average Generalization Error: "+aveRMSE); System.out.println("Minimum Generalization Error: "+minRMSE); System.out.println("Elapsed Time: "+mTot+" Miliseconds"); System.out.println("---------------------------------------------------------"); } /// Garbage collection //// private static long fSLEEP_INTERVAL = 20; private static long getMemoryUse(){ // collectGarbage(); // NOTE: To obtain the memory allocation w/o GC, comment this line. long totalMemory = Runtime.getRuntime().totalMemory(); long freeMemory = Runtime.getRuntime().freeMemory(); return (totalMemory - freeMemory); } private static void collectGarbage() { try { System.gc(); Thread.currentThread().sleep(fSLEEP_INTERVAL); System.runFinalization(); Thread.currentThread().sleep(fSLEEP_INTERVAL); } catch (InterruptedException ex){ ex.printStackTrace(); } } /** Configures & Starts the SimpleParity Network - Class Method * @param learningPatternNumber Number of Learning Patterns * @param testPatternNumber Number of Test Patterns */ private NeuralNet initializeSimpleParity(int learningPatternNumber,int testPatternNumber){ // Initialize the neural network NeuralNet network = new NeuralNet(); // Define & Initialize the Learning & Test inputs double[][] learningData = constructLearningData(learningPatternNumber); double[][] testData = constructTestData(testPatternNumber); // Define & Initialize the network layers and Define the layer names LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); input.setLayerName("Input Layer"); hidden.setLayerName("Hidden Layer"); output.setLayerName("Output Layer"); // Define the number of neurons for each layer input.setRows(4); hidden.setRows(4); output.setRows(1); // Define the input -> hidden connection FullSynapse synapseIH = new FullSynapse(); synapseIH.setName("IH Synapse"); // Define the hidden -> output connection FullSynapse synapseHO = new FullSynapse(); synapseHO.setName("HO Synapse"); // Connect the Input Layer with the Hidden Layer NeuralNetFactory.connect(input,synapseIH,hidden); // Connect the Hidden Layer with the Output Layer NeuralNetFactory.connect(hidden,synapseHO,output); // Define & Initialize the Learning Input Synapse MemoryInputSynapse learningInputSynapse = NeuralNetFactory.createInput("Learning Input Synapse",learningData,1,1,4); // Define the Test Input Synapse MemoryInputSynapse testInputSynapse = NeuralNetFactory.createInput("Test Input Synapse",testData,1,1,4); // Initialize the Input Switch Synapse LearningSwitch inputSwitch = NeuralNetFactory.createSwitch("Input Switch Synapse",learningInputSynapse,testInputSynapse); // Connect the Input Switch Synapse to the Input Layer input.addInputSynapse(inputSwitch); // Define the Trainer Input Switch MemoryInputSynapse learningDesiredSynapse = NeuralNetFactory.createInput("Learning Desired Synapse",learningData,1,5,5); // Define the Test Input Synapse MemoryInputSynapse testDesiredSynapse = NeuralNetFactory.createInput("Test Desired Synapse",testData,1,5,5); // Initialize the Input Switch Synapse LearningSwitch learningSwitch = NeuralNetFactory.createSwitch("Learning Switch Synapse",learningDesiredSynapse,testDesiredSynapse); // Define the Trainer and link it to the Monitor TeachingSynapse trainer = new TeachingSynapse(); trainer.setName("Simple Parity Trainer Synapse"); // Connect the Teacher to the Output Layer output.addOutputSynapse(trainer); // Connect the Learning Switch Synapse to the Trainer trainer.setDesired(learningSwitch); // Define the Output Synapse Memory (Data) MemoryOutputSynapse outputMemoryData = new MemoryOutputSynapse(); outputMemoryData.setName("Output Data"); // Connect the Output Memory Synapse (Data) to the Output output.addOutputSynapse(outputMemoryData); // Incorpore the network components to the NeuralNet object network.addLayer(input); network.addLayer(hidden); network.addLayer(output); network.setTeacher(trainer); network.getMonitor().setLearningRate(0.7); network.getMonitor().setMomentum(0.5); network.getMonitor().setTotCicles(totCycles); return network; } /** Constructs the network Learning Data based on the GUI options - Class Method * @param learningPatternNumber The int Number of Training Patterns * @return The Training Patterns Vector */ private double[][] constructLearningData(int learningPatternNumber){ // Define the number of columns int columns = 5; // Define the Learning Data array double[][] learningData = new double[learningPatternNumber][columns]; // Define the randomized Learning Data // Select the not Randomized patterns // The Simple Parity Input Data double[][] simpleParityData = { {0.0,0.0,0.0,0.0,1.0}, {0.0,0.0,0.0,1.0,0.0}, {0.0,0.0,1.0,0.0,0.0}, {0.0,0.0,1.0,1.0,1.0}, {0.0,1.0,0.0,0.0,0.0}, {0.0,1.0,0.0,1.0,1.0}, {0.0,1.0,1.0,0.0,1.0}, {0.0,1.0,1.0,1.0,0.0}, {1.0,0.0,0.0,0.0,0.0}, {1.0,0.0,0.0,1.0,1.0}, {1.0,0.0,1.0,0.0,1.0}, {1.0,0.0,1.0,1.0,0.0}, {1.0,1.0,0.0,0.0,1.0}, {1.0,1.0,0.0,1.0,0.0}, {1.0,1.0,1.0,0.0,0.0}, {1.0,1.0,1.0,1.0,1.0}}; for (int i = 0;i<learningPatternNumber;i++){ // Construct the each pattern of the Learning Data learningData[i][0] = simpleParityData[i][0]; learningData[i][1] = simpleParityData[i][1]; learningData[i][2] = simpleParityData[i][2]; learningData[i][3] = simpleParityData[i][3]; learningData[i][4] = simpleParityData[i][4]; } return learningData; } /** Constructs the network Test Data based on the GUI options - Class Method * @param testPatternNumber The int Number of Test Patterns * @return The Test Patterns Vector */ private double[][] constructTestData(int testPatternNumber){ // Define the number of columns int columns = 5; // Define the Learning Data array double[][] testData = new double[testPatternNumber][columns]; // Define the randomized Learning Data // Select the not Randomized patterns // The Simple Parity Input Data double[][] simpleParityData = {{0.0,0.0,0.0,0.0,1.0},{0.0,0.0,0.0,1.0,0.0},{0.0,0.0,1.0,0.0,0.0},{0.0,0.0,1.0,1.0,1.0},{0.0,1.0,0.0,0.0,0.0},{0.0,1.0,0.0,1.0,1.0},{0.0,1.0,1.0,0.0,1.0},{0.0,1.0,1.0,1.0,0.0},{1.0,0.0,0.0,0.0,0.0},{1.0,0.0,0.0,1.0,1.0},{1.0,0.0,1.0,0.0,1.0},{1.0,0.0,1.0,1.0,0.0},{1.0,1.0,0.0,0.0,1.0},{1.0,1.0,0.0,1.0,0.0},{1.0,1.0,1.0,0.0,0.0},{1.0,1.0,1.0,1.0,1.0}}; for (int i = 0;i<testPatternNumber;i++){ // Construct the each pattern of the Test Data testData[i][0] = simpleParityData[i][0]; testData[i][1] = simpleParityData[i][1]; testData[i][2] = simpleParityData[i][2]; testData[i][3] = simpleParityData[i][3]; testData[i][4] = simpleParityData[i][4]; } return testData; } private NeuralNet initializeModularParity(int learningPatternNumber,int testPatternNumber){ // Initialize the neural networks NeuralNet network = new NeuralNet(); NestedNeuralLayer firstNetwork = new NestedNeuralLayer(); NestedNeuralLayer secondNetwork = new NestedNeuralLayer(); // Set the First & Second network properties firstNetwork.setNeuralNet(xorNet); secondNetwork.setNeuralNet(xorNet); firstNetwork.setLayerName("First Network"); secondNetwork.setLayerName("Second Network"); //firstNetwork.setLearning(true); //secondNetwork.setLearning(true); // Define & Initialize the Learning & Test inputs double[][] learningData=constructLearningData(learningPatternNumber); double[][] testData=constructTestData(testPatternNumber); // Define & Initialize the network layers and Define the layer names LinearLayer inputFirst=new LinearLayer(); LinearLayer inputSecond=new LinearLayer(); SigmoidLayer hidden=new SigmoidLayer(); SigmoidLayer output=new SigmoidLayer(); inputFirst.setLayerName("First Input Third Network Layer"); inputSecond.setLayerName("Second Input Third Network Layer"); hidden.setLayerName("Hidden Third Network Layer"); output.setLayerName("Output Third Network Layer"); // Define the number of neurons for each layer inputFirst.setRows(1); inputSecond.setRows(1); hidden.setRows(2); output.setRows(1); // Define the first network output -> input connection for the third network DirectSynapse firstSynapseOI=new DirectSynapse(); firstSynapseOI.setName("First OI Synapse"); // Define the second network output -> input connection for the third network DirectSynapse secondSynapseOI=new DirectSynapse(); secondSynapseOI.setName("First OI Synapse"); // Define the first input -> hidden connection for the third network FullSynapse firstSynapseIH=new FullSynapse(); firstSynapseIH.setName("First IH Synapse"); // Define the Second input -> hidden connection for the third network FullSynapse secondSynapseIH=new FullSynapse(); secondSynapseIH.setName("Second IH Synapse"); // Define the hidden -> output connection for the third network FullSynapse synapseHO=new FullSynapse(); synapseHO.setName("HO Synapse"); // Connect the First Network with the First Input Third Network Layer NeuralNetFactory.connect(firstNetwork,firstSynapseOI,inputFirst); // Connect the Second Network with the Second Input Third Network Layer NeuralNetFactory.connect(secondNetwork,secondSynapseOI,inputSecond); // Connect the First Input Third Network Layer with the Hidden Third Network Layer NeuralNetFactory.connect(inputFirst,firstSynapseIH,hidden); // Connect the Second Input Third Network Layer with the Hidden Third Network Layer NeuralNetFactory.connect(inputSecond,secondSynapseIH,hidden); // Connect the Hidden Third Network Layer with the Output Third Network Layer NeuralNetFactory.connect(hidden,synapseHO,output); // Define & Initialize the First Learning Input Synapse MemoryInputSynapse firstLearningInputSynapse=NeuralNetFactory.createInput("First Learning Input Synapse",learningData,1,1,2); // Define the First Test Input Synapse MemoryInputSynapse firstTestInputSynapse=NeuralNetFactory.createInput("First Test Input Synapse",testData,1,1,2); // Initialize the First Input Switch Synapse LearningSwitch firstInputSwitch=NeuralNetFactory.createSwitch("First Input Switch Synapse",firstLearningInputSynapse,firstTestInputSynapse); // Connect the First Input Switch Synapse to the First Network firstNetwork.addInputSynapse(firstInputSwitch); // Define & Initialize the Second Learning Input Synapse MemoryInputSynapse secondLearningInputSynapse=NeuralNetFactory.createInput("Second Learning Input Synapse",learningData,1,3,4); // Define the Second Test Input Synapse MemoryInputSynapse secondTestInputSynapse=NeuralNetFactory.createInput("Second Test Input Synapse",testData,1,3,4); // Initialize the Second Input Switch Synapse LearningSwitch secondInputSwitch=NeuralNetFactory.createSwitch("Second Input Switch Synapse",secondLearningInputSynapse,secondTestInputSynapse); secondInputSwitch.setStepCounter(false); // Connect the Second Input Switch Synapse to the Second Network secondNetwork.addInputSynapse(secondInputSwitch); // Define the Trainer Input Switch MemoryInputSynapse learningDesiredSynapse=NeuralNetFactory.createInput("Learning Desired Synapse",learningData,1,5,5); // Define the Test Input Synapse MemoryInputSynapse testDesiredSynapse=NeuralNetFactory.createInput("Test Desired Synapse",testData,1,5,5); // Initialize the Input Switch Synapse LearningSwitch learningSwitch=NeuralNetFactory.createSwitch("Learning Switch Synapse",learningDesiredSynapse,testDesiredSynapse); // Define the Trainer and link it to the Monitor TeachingSynapse trainer=new TeachingSynapse(); trainer.setName("Modular Parity Trainer Synapse"); // Connect the Teacher to the Output Layer output.addOutputSynapse(trainer); // Connect the Learning Switch Synapse to the Trainer trainer.setDesired(learningSwitch); // Define the Output Synapse Memory (Data) MemoryOutputSynapse outputMemoryData=new MemoryOutputSynapse(); outputMemoryData.setName("Output Data"); // Connect the Output Memory Synapse (Data) to the Output Third Network Layer output.addOutputSynapse(outputMemoryData); // Incorpore the network components to the NeuralNet object network.addLayer(firstNetwork); network.addLayer(secondNetwork); network.addLayer(inputFirst); network.addLayer(inputSecond); network.addLayer(hidden); network.addLayer(output); network.setTeacher(trainer); network.getMonitor().setLearningRate(0.5); network.getMonitor().setMomentum(0.5); network.getMonitor().setTotCicles(totCycles); return network; } /** Initializes the EETNN Neural Network I - Class Method * @param learningPatternNumber Number of Learning Patterns * @param testPatternNumber Number of Test Patterns */ private NeuralNet initializeNetworkI(int learningPatternNumber,int testPatternNumber){ // Initialize the neural network NeuralNet network=new NeuralNet(); // Define & Initialize the network layers and Define the layer names LinearLayer input=new LinearLayer(); SigmoidLayer hidden=new SigmoidLayer(); SigmoidLayer output=new SigmoidLayer(); input.setLayerName("Input Layer"); hidden.setLayerName("Hidden Layer"); output.setLayerName("Output Layer"); // Define the number of neurons for each layer input.setRows(2); hidden.setRows(2); output.setRows(1); // Define the input -> hidden connection FullSynapse synapseIH=new FullSynapse(); synapseIH.setName("IH Synapse"); // Define the hidden -> output connection FullSynapse synapseHO=new FullSynapse(); synapseHO.setName("HO Synapse"); // Connect the Input Layer with the Hidden Layer NeuralNetFactory.connect(input,synapseIH,hidden); // Connect the Hidden Layer with the Output Layer NeuralNetFactory.connect(hidden,synapseHO,output); // Define & Initialize the Learning Input Synapse XLSInputSynapse learningInputSynapse = new XLSInputSynapse(); learningInputSynapse.setName("Learning Input Synapse"); learningInputSynapse.setInputFile(new File("/tmp/wine.xls")); learningInputSynapse.setAdvancedColumnSelector("6,7"); learningInputSynapse.setSheetName("wine.data"); learningInputSynapse.setFirstRow(2); learningInputSynapse.setLastRow(100); // Define the Test Input Synapse XLSInputSynapse testInputSynapse = new XLSInputSynapse(); testInputSynapse.setName("Test Input Synapse"); testInputSynapse.setInputFile(new File("/tmp/wine.xls")); testInputSynapse.setAdvancedColumnSelector("6,7"); testInputSynapse.setSheetName("wine.data"); testInputSynapse.setFirstRow(2); testInputSynapse.setLastRow(100); // Initialize the Input Switch Synapse LearningSwitch inputSwitch=NeuralNetFactory.createSwitch("Input Switch Synapse",learningInputSynapse,testInputSynapse); // Connect the Input Switch Synapse to the Input Layer input.addInputSynapse(inputSwitch); // Define the Trainer's Learning Input Synapse XLSInputSynapse learningDesiredSynapse = new XLSInputSynapse(); learningDesiredSynapse.setName("Learning Desired Synapse"); learningDesiredSynapse.setInputFile(new File("/tmp/wine.xls")); learningDesiredSynapse.setAdvancedColumnSelector("8"); learningDesiredSynapse.setSheetName("wine.data"); learningDesiredSynapse.setFirstRow(2); learningDesiredSynapse.setLastRow(100); // Define the Trainer's Test Input Synapse XLSInputSynapse testDesiredSynapse = new XLSInputSynapse(); testDesiredSynapse.setName("Test Desired Synapse"); testDesiredSynapse.setInputFile(new File("/tmp/wine.xls")); testDesiredSynapse.setAdvancedColumnSelector("8"); testDesiredSynapse.setSheetName("wine.data"); testDesiredSynapse.setFirstRow(2); testDesiredSynapse.setLastRow(100); // Initialize the Input Switch Synapse LearningSwitch learningSwitch=NeuralNetFactory.createSwitch("Learning Switch Synapse",learningDesiredSynapse,testDesiredSynapse); // Define the Trainer and link it to the Monitor TeachingSynapse trainer=new TeachingSynapse(); trainer.setName("EETNN Trainer Synapse"); // Connect the Teacher to the Output Layer output.addOutputSynapse(trainer); // Connect the Learning Switch Synapse to the Trainer trainer.setDesired(learningSwitch); // Define the Output Synapse Memory (Data) /*XLSOutputSynapse outputMemoryData=new XLSOutputSynapse(); outputMemoryData.setName("Output Data"); outputMemoryData.setFileName("/tmp/OutputData.xls"); outputMemoryData.setSheetName("wine.data"); // Connect the Output Memory Synapse (Data) to the Output output.addOutputSynapse(outputMemoryData); */ // Incorpore the network components to the NeuralNet object network.addLayer(input); network.addLayer(hidden); network.addLayer(output); network.setTeacher(trainer); return network; } }
Java
/* * NeuralNetFactory.java * * Created on 1 marzo 2004, 21.21 */ package org.joone.samples.engine.validation; import org.joone.engine.*; import org.joone.io.*; import org.joone.util.*; /** * <p>Title: Effort Estimations Through Neural Networks</p> * <p>Description: Stage II - Joone Pilot</p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: Motorola</p> * @author Sebastian Donatti - AGD013 * @version 1.0.0 */ public class NeuralNetFactory{ /** Connects two Layers with a Synapse - Class Method * @param ly1 Origin Layer * @param syn Synapse * @param ly2 Ending Layer */ public static void connect(Layer ly1,Synapse syn,Layer ly2){ ly1.addOutputSynapse(syn); ly2.addInputSynapse(syn); } /** Creates a LearningSwitch and attach to it both the training and the validation input synapses - Class Method * @param name The LearningSwitch Name * @param IT The Input Synapse (Training) * @param IV The Input Synapse (Test) * @return LearningSwitch */ public static LearningSwitch createSwitch(String name,StreamInputSynapse IT,StreamInputSynapse IV){ LearningSwitch lsw = new LearningSwitch(); lsw.setName(name); lsw.addTrainingSet(IT); lsw.addValidationSet(IV); return lsw; } /** Creates a MemoryInputSynapse - Class Method * @param name The Synapse Name * @param inData The Synapse Input Data * @param firstRow The First Row * @param firstCol The First Column * @param lastCol The Last Column * @return The MemoryInputSynapse */ public static MemoryInputSynapse createInput(String name,double[][] inData,int firstRow,int firstCol,int lastCol){ MemoryInputSynapse input = new MemoryInputSynapse(); input.setName(name); input.setInputArray(inData); input.setFirstRow(firstRow); if (firstCol!=lastCol){ input.setAdvancedColumnSelector(firstCol+"-"+lastCol); } else{ input.setAdvancedColumnSelector(Integer.toString(firstCol)); } return input; } }
Java
/* * ValidationSample.java * * Created on 11 november 2002, 22.59 * @author pmarrone */ package org.joone.samples.engine.validation; import java.io.File; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.net.*; import org.joone.io.*; import org.joone.util.*; /** * This example shows how to check the training level of the net * using a validation data source. * In this example we will learn to use the following objects: * - org.joone.util.LearningSwitch * - org.joone.net.NeuralNetValidator * - org.joone.util.NormalizerPlugIn * * This program shows how to build the same kind of neural net as that * contained into the org/joone/samples/editor/scripting/ValidationSample.ser * file using only java code and the core engine's API. Open that net in * the GUI editor to see the architecture of the net built in this example. */ public class SimpleValidationSample implements NeuralNetListener, NeuralValidationListener { NeuralNet net; long startms; private static String filePath = "org/joone/samples/engine/validation"; /** Creates a new instance of SampleScript */ public SimpleValidationSample() { } /** * @param args the command line arguments */ public static void main(String[] args) { SimpleValidationSample sampleNet = new SimpleValidationSample(); sampleNet.initialize(filePath); sampleNet.start(); } private void initialize(String path) { /* Creates the three layers and connect them */ LinearLayer ILayer = new LinearLayer(); // Input Layer SigmoidLayer HLayer = new SigmoidLayer(); // Hidden Layer SigmoidLayer OLayer = new SigmoidLayer(); // Output Layer ILayer.setRows(13); // The input pattern has 13 columns HLayer.setRows(4); OLayer.setRows(1); // The desired pattern has 1 column FullSynapse synIH = new FullSynapse(); FullSynapse synHO = new FullSynapse(); this.connect(ILayer, synIH, HLayer); this.connect(HLayer, synHO, OLayer); /* Creates all the required input data sets */ FileInputSynapse ITdata = this.createInput(path+"/wine.txt",1,2,14); /* The input training data set */ FileInputSynapse IVdata = this.createInput(path+"/wine.txt",131,2,14); /* The input validation data set */ FileInputSynapse DTdata = this.createInput(path+"/wine.txt",1,1,1); /* The desired training data set */ FileInputSynapse DVdata = this.createInput(path+"/wine.txt",131,1,1); /* The desired validation data set */ /* Creates and attach the input learning switch */ LearningSwitch Ilsw = this.createSwitch(ITdata, IVdata); ILayer.addInputSynapse(Ilsw); /* Creates and attach the desired learning switch */ LearningSwitch Dlsw = this.createSwitch(DTdata, DVdata); TeachingSynapse ts = new TeachingSynapse(); // The teacher of the net ts.setDesired(Dlsw); OLayer.addOutputSynapse(ts); /* Now we put all togheter into a NeuralNet object */ net = new NeuralNet(); net.addLayer(ILayer, NeuralNet.INPUT_LAYER); net.addLayer(HLayer, NeuralNet.HIDDEN_LAYER); net.addLayer(OLayer, NeuralNet.OUTPUT_LAYER); net.setTeacher(ts); /* Sets the Monitor's parameters */ Monitor mon = net.getMonitor(); mon.setLearningRate(0.4); mon.setMomentum(0.5); mon.setTrainingPatterns(130); mon.setValidationPatterns(48); mon.setTotCicles(1000); mon.setLearning(true); } /** Creates a FileInputSynapse */ private FileInputSynapse createInput(String name, int firstRow, int firstCol, int lastCol) { FileInputSynapse input = new FileInputSynapse(); input.setInputFile(new File(name)); input.setFirstRow(firstRow); if (firstCol != lastCol) input.setAdvancedColumnSelector(firstCol+"-"+lastCol); else input.setAdvancedColumnSelector(Integer.toString(firstCol)); // We normalize the input data in the range 0 - 1 NormalizerPlugIn norm = new NormalizerPlugIn(); if (firstCol != lastCol) norm.setAdvancedSerieSelector("1-"+Integer.toString(lastCol-firstCol+1)); else norm.setAdvancedSerieSelector("1"); norm.setMin(0.1); norm.setMax(0.9); input.addPlugIn(norm); return input; } /** Connects two Layers with a Synapse */ private void connect(Layer ly1, Synapse syn, Layer ly2) { ly1.addOutputSynapse(syn); ly2.addInputSynapse(syn); } /* Creates a LearningSwitch and attach to it both the training and the desired input synapses */ private LearningSwitch createSwitch(StreamInputSynapse IT, StreamInputSynapse IV) { LearningSwitch lsw = new LearningSwitch(); lsw.addTrainingSet(IT); lsw.addValidationSet(IV); return lsw; } private void start() { // Registers itself as a listener net.getMonitor().addNeuralNetListener(this); startms = System.currentTimeMillis(); net.go(); } /* Events */ public void netValidated(NeuralValidationEvent event) { // Shows the RMSE at the end of the cycle NeuralNet NN = (NeuralNet)event.getSource(); System.out.println(" Validation Error: "+NN.getMonitor().getGlobalError()); } public void cicleTerminated(NeuralNetEvent e) { // Prints out the cycle and the training error int cycle = net.getMonitor().getTotCicles() - net.getMonitor().getCurrentCicle()+1; if (cycle % 200 == 0) { // We validate the net every 200 cycles System.out.println("Cycle #"+cycle); System.out.println(" Training Error: " + net.getMonitor().getGlobalError()); // Creates a copy of the neural network net.getMonitor().setExporting(true); NeuralNet newNet = net.cloneNet(); net.getMonitor().setExporting(false); // Cleans the old listeners // This is a fundamental action to avoid that the validating net // calls the cicleTerminated method of this class newNet.removeAllListeners(); // Set all the parameters for the validation NeuralNetValidator nnv = new NeuralNetValidator(newNet); nnv.addValidationListener(this); nnv.start(); // Validates the net } } public void errorChanged(NeuralNetEvent e) { // Monitor NN = (Monitor)e.getSource(); // System.out.println(" Actual training error: "+NN.getGlobalError()); } public void netStarted(NeuralNetEvent e) { } public void netStopped(NeuralNetEvent e) { System.out.println("Stopped after "+(System.currentTimeMillis()-startms)+" ms"); } public void netStoppedError(NeuralNetEvent e,String error) { } }
Java
package org.joone.samples.engine.xor.rbf; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.*; import java.util.Vector; /** * Very simple example of the Gaussian (static and random centers) RBF solving the XOR problem. * * @author Boris Jansen */ public class XOR_static_RBF implements NeuralNetListener { /** The neural network. */ private NeuralNet nnet = null; /** The RBF hidden layer. */ RbfGaussianLayer hidden = null; /** Synapses. */ private MemoryInputSynapse inputSynapse, desiredOutputSynapse; private MemoryOutputSynapse outputSynapse; /** If the following flag is true, the centers will be chosen randomly. * Otherwise it will use predefined, fixed centers (able to solve the XOR * problem. */ private boolean randomCenters = false; // XOR input private double[][] inputArray = new double[][] { {0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 1.0} }; // XOR desired output private double[][] desiredOutputArray = new double[][] { {1.0}, {0.0}, {0.0}, {1.0} }; /** * Main * * @param args the command line arguments */ public static void main(String args[]) { XOR_static_RBF xor = new XOR_static_RBF(); xor.initNeuralNet(); xor.train(); xor.test(); } /** * Method declaration */ public void train() { // set the inputs inputSynapse.setInputArray(inputArray); inputSynapse.setAdvancedColumnSelector("1,2"); // set the desired outputs desiredOutputSynapse.setInputArray(desiredOutputArray); desiredOutputSynapse.setAdvancedColumnSelector("1"); // get the monitor object to train or feed forward Monitor monitor = nnet.getMonitor(); // set the monitor parameters monitor.setLearningRate(0.3); monitor.setMomentum(0.8); monitor.setTrainingPatterns(inputArray.length); monitor.setTotCicles(200); // RPROP parameters (uncomment if you want to use the RPROP learning algorithm) //monitor.getLearners().add(0, "org.joone.engine.RpropLearner"); //monitor.setBatchSize(4); //monitor.setLearningMode(0); monitor.setLearning(true); nnet.addNeuralNetListener(this); nnet.go(true); } /** * Create and init the neural network. */ protected void initNeuralNet() { // First create the three layers LinearLayer input = new LinearLayer(); hidden = new RbfGaussianLayer(); //SigmoidLayer output = new SigmoidLayer(); // you can try it (not a traditional RBF network) BiasedLinearLayer output = new BiasedLinearLayer(); // set the dimensions of the layers input.setRows(2); hidden.setRows(2); output.setRows(1); if(!randomCenters) { // Use static Gaussian RBFs RbfGaussianParameters[] myParameters = new RbfGaussianParameters[2]; double[] myMean0 = {0.0, 0.0}; myParameters[0] = new RbfGaussianParameters(myMean0, Math.sqrt(.5)); double[] myMean1 = {1.0, 1.0}; myParameters[1] = new RbfGaussianParameters(myMean1, Math.sqrt(.5)); hidden.setGaussianParameters(myParameters); } // Now create the two synapses RbfInputSynapse synapse_IH = new RbfInputSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); // the input to the neural net inputSynapse = new MemoryInputSynapse(); input.addInputSynapse(inputSynapse); if(randomCenters) { hidden.useRandomCenter(inputSynapse); } // The Trainer and its desired output desiredOutputSynapse = new MemoryInputSynapse(); TeachingSynapse trainer = new TeachingSynapse(); trainer.setDesired(desiredOutputSynapse); // Now we add this structure to a NeuralNet object nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); output.addOutputSynapse(trainer); } public void test() { // attach a MemoryOutputSynapse to the output of the neural net outputSynapse = new MemoryOutputSynapse(); nnet.getOutputLayer().addOutputSynapse(outputSynapse); nnet.getMonitor().setTotCicles(1); nnet.getMonitor().setTrainingPatterns(4); nnet.getMonitor().setLearning(false); nnet.removeAllListeners(); nnet.go(); System.out.println("Outputs"); System.out.println("-------"); for(int i = 0; i < 4; i++) { double[] myPattern = outputSynapse.getNextPattern(); System.out.println("Output: " + myPattern[0]); } System.out.println("Centers RBF neurons: "); RbfGaussianParameters[] myParams = hidden.getGaussianParameters(); for(int i = 0; i < myParams.length; i++) { String myText = (i+1) + ": [center: "; for(int j = 0; j < myParams[i].getMean().length; j++) { myText += myParams[i].getMean()[j] + ", "; } myText += "Std dev: " + myParams[i].getStdDeviation() + "]"; System.out.println(myText); } } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); if (mon.getCurrentCicle() % 100 == 0) System.out.println("Epoch: "+(mon.getTotCicles()-mon.getCurrentCicle())+" RMSE:"+mon.getGlobalError()); } public void netStarted(NeuralNetEvent e) { } public void netStopped(NeuralNetEvent e) { } public void netStoppedError(NeuralNetEvent e, String error) { } }
Java
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ /* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net * * XORMemory.java * */ package org.joone.samples.engine.xor; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.NeuralNet; /** * Sample class to demostrate the use of the MemoryInputSynapse * * @author Jos�?Rodriguez */ public class XORMemory implements NeuralNetListener { // XOR input private double[][] inputArray = new double[][] { {0.0, 0.0, 0.0}, {0.0, 1.0, 1.0}, {1.0, 0.0, 1.0}, {1.0, 1.0, 0.0} }; private long mills; /** * @param args the command line arguments */ public static void main(String args[]) { XORMemory xor = new XORMemory(); if (args.length == 0) xor.Go(10000); else xor.Go(new Integer(args[0]).intValue()); } /** * Method declaration */ public void Go(int epochs) { // Firts, creates the three Layers LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); input.setLayerName("input"); hidden.setLayerName("hidden"); output.setLayerName("output"); // sets their dimensions input.setRows(2); hidden.setRows(3); output.setRows(1); // Now create the two Synapses FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ synapse_IH.setName("IH"); synapse_HO.setName("HO"); // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); MemoryInputSynapse inputStream = new MemoryInputSynapse(); // The first two columns contain the input values inputStream.setInputArray(inputArray); inputStream.setAdvancedColumnSelector("1,2"); // set the input data input.addInputSynapse(inputStream); TeachingSynapse trainer = new TeachingSynapse(); // Setting of the file containing the desired responses provided by a FileInputSynapse MemoryInputSynapse samples = new MemoryInputSynapse(); // The output values are on the third column of the file samples.setInputArray(inputArray); samples.setAdvancedColumnSelector("3"); trainer.setDesired(samples); // Connects the Teacher to the last layer of the net output.addOutputSynapse(trainer); // Creates a new NeuralNet NeuralNet nnet = new NeuralNet(); /* * All the layers must be inserted in the NeuralNet object */ nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); Monitor monitor = nnet.getMonitor(); monitor.setTrainingPatterns(4); // # of rows (patterns) contained in the input file monitor.setTotCicles(epochs); // How many times the net must be trained on the input patterns monitor.setLearningRate(0.8); monitor.setMomentum(0.5); monitor.setLearning(true); // The net must be trained monitor.setSingleThreadMode(true); // Set to false for multi-thread mode /* The application registers itself as monitor's listener so it can receive the notifications of termination from the net. */ monitor.addNeuralNetListener(this); mills = System.currentTimeMillis(); nnet.go(); // The net starts in async mode } /** * Method declaration */ public void netStopped(NeuralNetEvent e) { long delay = System.currentTimeMillis() - mills; System.out.println("Training finished after "+delay+" ms"); System.exit(0); } /** * Method declaration */ public void cicleTerminated(NeuralNetEvent e) { } /** * Method declaration */ public void netStarted(NeuralNetEvent e) { System.out.println("Training..."); } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor) e.getSource(); long c = mon.getCurrentCicle(); long cl = c / 1000; // We want to print the results every 1000 cycles if ((cl * 1000) == c) { System.out.println(c + " cycles remaining - Error = " + mon.getGlobalError()); } } public void netStoppedError(NeuralNetEvent e,String error) { } } /*--- formatting done in "JMRA based on Sun Java Convention" style on 05-08-2002 ---*/
Java
/* * XOR.java * Sample class to demostrate the use of the Joone's core engine * see the Developer Guide for more details */ /* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net */ package org.joone.samples.engine.xor; import java.io.File; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.NeuralNet; public class XOR implements NeuralNetListener { private static String inputData = "src/org/joone/samples/engine/xor/xor.txt"; private static String outputFile = "src/org/joone/samples/engine/xor/xorout2.txt"; /** Creates new XOR */ public XOR() { } /** * @param args the command line arguments */ public static void main(String args[]) { XOR xor = new XOR(); xor.Go(inputData, outputFile); } public void Go(String inputFile, String outputFile) { /* * Firts, creates the three Layers */ LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); input.setLayerName("input"); hidden.setLayerName("hidden"); output.setLayerName("output"); /* sets their dimensions */ input.setRows(2); hidden.setRows(3); output.setRows(1); /* * Now create the two Synapses */ FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ synapse_IH.setName("IH"); synapse_HO.setName("HO"); /* * Connect the input layer whit the hidden layer */ input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); /* * Connect the hidden layer whit the output layer */ hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); FileInputSynapse inputStream = new FileInputSynapse(); /* The first two columns contain the input values */ inputStream.setAdvancedColumnSelector("1,2"); /* This is the file that contains the input data */ inputStream.setInputFile(new File(inputFile)); input.addInputSynapse(inputStream); TeachingSynapse trainer = new TeachingSynapse(); /* Setting of the file containing the desired responses, provided by a FileInputSynapse */ FileInputSynapse samples = new FileInputSynapse(); samples.setInputFile(new File(inputFile)); /* The output values are on the third column of the file */ samples.setAdvancedColumnSelector("3"); trainer.setDesired(samples); /* Creates the error output file */ FileOutputSynapse error = new FileOutputSynapse(); error.setFileName(outputFile); //error.setBuffered(false); trainer.addResultSynapse(error); /* Connects the Teacher to the last layer of the net */ output.addOutputSynapse(trainer); NeuralNet nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); // Gets the Monitor object and set the learning parameters Monitor monitor = nnet.getMonitor(); monitor.setLearningRate(0.8); monitor.setMomentum(0.3); /* The application registers itself as monitor's listener * so it can receive the notifications of termination from * the net. */ monitor.addNeuralNetListener(this); monitor.setTrainingPatterns(4); /* # of rows (patterns) contained in the input file */ monitor.setTotCicles(10); /* How many times the net must be trained on the input patterns */ monitor.setLearning(true); /* The net must be trained */ nnet.go(); /* The net starts the training job */ } public void netStopped(NeuralNetEvent e) { System.out.println("Training finished"); } public void cicleTerminated(NeuralNetEvent e) { } public void netStarted(NeuralNetEvent e) { System.out.println("Training..."); } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); /* We want print the results every 200 cycles */ // if (mon.getCurrentCicle() % 1 == 0) System.out.println(mon.getCurrentCicle() + " epochs remaining - RMSE = " + mon.getGlobalError()); } public void netStoppedError(NeuralNetEvent e,String error) { } }
Java
/* * EmbeddedXOR.java * * Created on 7 maggio 2002, 19.27 */ package org.joone.samples.engine.xor; import org.joone.log.*; import org.joone.engine.*; import org.joone.io.*; import org.joone.net.NeuralNet; import java.io.*; import org.joone.util.UnNormalizerOutputPlugIn; /** * This example shows the use of a neural network embedded in another * application that gets the output from the MemoryOutputSynapse object * querying the neural network with a predefined set of patterns * * @author pmarrone */ public class EmbeddedXOR { private static final ILogger log = LoggerFactory.getLogger(EmbeddedXOR.class); private double[][] inputArray = { {0, 0}, {0, 1}, {1, 0}, {1, 1} }; private MemoryOutputSynapse memOut; private static String xorNet = "org/joone/samples/engine/xor/xor.snet"; /** Creates a new instance of EmbeddedXOR */ public EmbeddedXOR() { } /** * @param args the command line arguments */ public static void main(String[] args) { EmbeddedXOR xor = new EmbeddedXOR(); xor.Go(xorNet); } private void Go(String fileName) { // We load the serialized XOR neural net NeuralNet xor = restoreNeuralNet(fileName); if (xor != null) { /* We get the first layer of the net (the input layer), then remove all the input synapses attached to it and attach a MemoryInputSynapse */ Layer input = xor.getInputLayer(); input.removeAllInputs(); MemoryInputSynapse memInp = new MemoryInputSynapse(); memInp.setFirstRow(1); memInp.setAdvancedColumnSelector("1,2"); input.addInputSynapse(memInp); memInp.setInputArray(inputArray); /* We get the last layer of the net (the output layer), then remove all the output synapses attached to it and attach a MemoryOutputSynapse */ Layer output = xor.getOutputLayer(); output.removeAllOutputs(); memOut = new MemoryOutputSynapse(); // Inserts an output plugin to set the output range to [1, 2] // (just to demonstrate how to use an UnNormalizerPlugin) UnNormalizerOutputPlugIn outPlugin = new UnNormalizerOutputPlugIn(); outPlugin.setAdvancedSerieSelector("1"); outPlugin.setOutDataMin(1); outPlugin.setOutDataMax(2); memOut.addPlugIn(outPlugin); output.addOutputSynapse(memOut); // Now we interrogate the net once with four input patterns xor.getMonitor().setTotCicles(1); xor.getMonitor().setTrainingPatterns(4); xor.getMonitor().setLearning(false); interrogate(xor, 10); log.info("Finished"); } } private void interrogate(NeuralNet net, int times) { int cc = net.getMonitor().getTrainingPatterns(); for (int t=0; t < times; ++t) { log.info("Launch #"+(t+1)); net.go(); for (int i=0; i < cc; ++i) { // Read the next pattern and print out it double[] pattern = memOut.getNextPattern(); log.info(" Output Pattern #"+(i+1)+" = "+pattern[0]); } net.stop(); } } private NeuralNet restoreNeuralNet(String fileName) { NeuralNet nnet = null; try { FileInputStream stream = new FileInputStream(fileName); ObjectInput input = new ObjectInputStream(stream); nnet = (NeuralNet)input.readObject(); } catch (Exception e) { log.warn( "Exception was thrown. Message is : " + e.getMessage(), e ); } return nnet; } }
Java
/* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net * * XOR_using_NeuralNet.java * */ package org.joone.samples.engine.xor; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.*; import java.util.Vector; /** * Sample class to demostrate the use of the MemoryInputSynapse * * @author Jos�?Rodriguez */ public class XOR_using_NeuralNet implements NeuralNetListener { private NeuralNet nnet = null; private MemoryInputSynapse inputSynapse, desiredOutputSynapse; private MemoryOutputSynapse outputSynapse; LinearLayer input; SigmoidLayer hidden, output; boolean singleThreadMode = true; // XOR input private double[][] inputArray = new double[][] { {0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 1.0} }; // XOR desired output private double[][] desiredOutputArray = new double[][] { {0.0}, {1.0}, {1.0}, {0.0} }; /** * @param args the command line arguments */ public static void main(String args[]) { XOR_using_NeuralNet xor = new XOR_using_NeuralNet(); xor.initNeuralNet(); xor.train(); xor.interrogate(); } /** * Method declaration */ public void train() { // set the inputs inputSynapse.setInputArray(inputArray); inputSynapse.setAdvancedColumnSelector("1,2"); // set the desired outputs desiredOutputSynapse.setInputArray(desiredOutputArray); desiredOutputSynapse.setAdvancedColumnSelector("1"); // get the monitor object to train or feed forward Monitor monitor = nnet.getMonitor(); // set the monitor parameters monitor.setLearningRate(0.8); monitor.setMomentum(0.3); monitor.setTrainingPatterns(inputArray.length); monitor.setTotCicles(5000); monitor.setLearning(true); long initms = System.currentTimeMillis(); // Run the network in single-thread, synchronized mode nnet.getMonitor().setSingleThreadMode(singleThreadMode); nnet.go(true); System.out.println("Total time= "+(System.currentTimeMillis() - initms)+" ms"); } private void interrogate() { // set the inputs inputSynapse.setInputArray(inputArray); inputSynapse.setAdvancedColumnSelector("1,2"); Monitor monitor=nnet.getMonitor(); monitor.setTrainingPatterns(4); monitor.setTotCicles(1); monitor.setLearning(false); FileOutputSynapse foutput=new FileOutputSynapse(); // set the output synapse to write the output of the net foutput.setFileName("/tmp/xorOut.txt"); if(nnet!=null) { nnet.addOutputSynapse(foutput); System.out.println(nnet.check()); nnet.getMonitor().setSingleThreadMode(singleThreadMode); nnet.go(); } } /** * Method declaration */ protected void initNeuralNet() { // First create the three layers input = new LinearLayer(); hidden = new SigmoidLayer(); output = new SigmoidLayer(); // set the dimensions of the layers input.setRows(2); hidden.setRows(3); output.setRows(1); input.setLayerName("L.input"); hidden.setLayerName("L.hidden"); output.setLayerName("L.output"); // Now create the two Synapses FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); // the input to the neural net inputSynapse = new MemoryInputSynapse(); input.addInputSynapse(inputSynapse); // The Trainer and its desired output desiredOutputSynapse = new MemoryInputSynapse(); TeachingSynapse trainer = new TeachingSynapse(); trainer.setDesired(desiredOutputSynapse); // Now we add this structure to a NeuralNet object nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); output.addOutputSynapse(trainer); nnet.addNeuralNetListener(this); } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); if (mon.getCurrentCicle() % 100 == 0) System.out.println("Epoch: "+(mon.getTotCicles()-mon.getCurrentCicle())+" RMSE:"+mon.getGlobalError()); } public void netStarted(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); System.out.print("Network started for "); if (mon.isLearning()) System.out.println("training."); else System.out.println("interrogation."); } public void netStopped(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); System.out.println("Network stopped. Last RMSE="+mon.getGlobalError()); } public void netStoppedError(NeuralNetEvent e, String error) { System.out.println("Network stopped due the following error: "+error); } }
Java
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ /* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net */ package org.joone.samples.engine.xor; import java.io.Serializable; import java.util.Vector; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.engine.listeners.*; import org.joone.net.*; import org.joone.util.LearningSwitch; import org.joone.samples.util.ParityInputSynapse; import org.joone.io.*; /** * Sample class to demostrate the use of the FahlmanTeacherSynapse and related classes. */ public class XORFahlman implements Serializable, NeuralNetListener, NeuralValidationListener { /** The NN. */ private NeuralNet nnet = null; /** FIFO-queue to remember at which cycle the fahlman criterion was fullfilled. */ private Vector validationCycles = new Vector(); private long mills; /** * @param args the command line arguments */ public static void main(String args[]) { XORFahlman xor = new XORFahlman(); xor.Go(); } /** * Method declaration */ public void Go() { // Firts, creates the three Layers LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); input.setLayerName("input"); hidden.setLayerName("hidden"); output.setLayerName("output"); // sets their dimensions input.setRows(2); hidden.setRows(3); output.setRows(1); // Now create the two Synapses FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ synapse_IH.setName("IH"); synapse_HO.setName("HO"); // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); ParityInputSynapse inputStream = new ParityInputSynapse(); inputStream.setParitySize(2); // size 2 equals XOR problem InputConnector myInputData = new InputConnector(); myInputData.setInputSynapse(inputStream); myInputData.setAdvancedColumnSelector("1-2"); InputConnector myInputValData = new InputConnector(); myInputValData.setInputSynapse(inputStream); myInputValData.setAdvancedColumnSelector("1-2"); LearningSwitch mySwitch = new LearningSwitch(); mySwitch.addTrainingSet(myInputData); mySwitch.addValidationSet(myInputValData); input.addInputSynapse(mySwitch); FahlmanTeacherSynapse myFahlman = new FahlmanTeacherSynapse(); InputConnector myDesiredData = new InputConnector(); myDesiredData.setInputSynapse(inputStream); myDesiredData.setAdvancedColumnSelector("3"); InputConnector myDesiredValData = new InputConnector(); myDesiredValData.setInputSynapse(inputStream); myDesiredValData.setAdvancedColumnSelector("3"); LearningSwitch myOutputSwitch = new LearningSwitch(); myOutputSwitch.addTrainingSet(myDesiredData); myOutputSwitch.addValidationSet(myDesiredValData); TeachingSynapse trainer = new TeachingSynapse(myFahlman); trainer.setDesired(myOutputSwitch); // Connects the Teacher to the last layer of the net output.addOutputSynapse(trainer); nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); nnet.getMonitor().setTrainingPatterns(4); nnet.getMonitor().setValidationPatterns(4); nnet.getMonitor().setTotCicles(10000); nnet.getMonitor().setLearning(true); nnet.getMonitor().setLearningRate(0.8); nnet.getMonitor().setMomentum(0.3); mills = System.currentTimeMillis(); nnet.addNeuralNetListener(this); nnet.go(); } /** * Method declaration */ public void netStopped(NeuralNetEvent e) { long delay = System.currentTimeMillis() - mills; System.out.println("Training finished after "+delay+" ms"); System.exit(0); } public void cicleTerminated(NeuralNetEvent e) { Monitor mon = (Monitor) e.getSource(); long c = mon.getCurrentCicle(); // We validate each 200 epochs if (c % 200 == 0) { nnet.getMonitor().setExporting(true); NeuralNet myClone = nnet.cloneNet(); nnet.getMonitor().setExporting(false); myClone.removeAllListeners(); myClone.getMonitor().setParam(FahlmanTeacherSynapse.CRITERION, Boolean.TRUE); NeuralNetValidator myValidator = new NeuralNetValidator(myClone); myValidator.addValidationListener(this); validationCycles.add(new Integer(nnet.getMonitor().getTotCicles() - nnet.getMonitor().getCurrentCicle())); myValidator.start(); } } /** * Method declaration */ public void netStarted(NeuralNetEvent e) { System.out.println("Training..."); } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor) e.getSource(); long c = mon.getCurrentCicle(); if (c % 100 == 0) { System.out.println(c + " cycles remaining - Error = " + mon.getGlobalError()); } } public void netStoppedError(NeuralNetEvent e,String error) { } public void netValidated(NeuralValidationEvent event) { Monitor myMonitor = ((NeuralNet)event.getSource()).getMonitor(); if(myMonitor.getParam("FAHLMAN_CRITERION") != null && ((Boolean)myMonitor.getParam("FAHLMAN_CRITERION")).booleanValue()) { if (nnet.isRunning()) { nnet.stop(); System.out.println("Fahlman criterion fulfilled (at cycle " + ((Integer)validationCycles.get(0)).intValue() + ")..."); } } validationCycles.remove(0); } }
Java
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ /* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net * * XORMemory.java * */ package org.joone.samples.engine.xor.InputConnector; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.NeuralNet; import org.joone.util.*; /** * Sample class to demostrate the use of the MemoryInputSynapse * * @author P.Marrone */ public class XORMemory_using_InputConnector implements NeuralNetListener { // XOR input private double[][] inputArray = new double[][] { {0.0, 0.0, 0.0}, {0.0, 1.0, 1.0}, {1.0, 0.0, 1.0}, {1.0, 1.0, 0.0} }; private long mills; /** * @param args the command line arguments */ public static void main(String args[]) { XORMemory_using_InputConnector xor = new XORMemory_using_InputConnector(); xor.Go(); } /** * Method declaration */ public void Go() { // Firts, creates the three Layers LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); input.setLayerName("input"); hidden.setLayerName("hidden"); output.setLayerName("output"); // sets their dimensions input.setRows(2); hidden.setRows(3); output.setRows(1); // Now create the two Synapses FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ synapse_IH.setName("IH"); synapse_HO.setName("HO"); // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); // Set the input data // as we want to use the InputConnectors, we read all the three input columns MemoryInputSynapse inputStream = new MemoryInputSynapse(); inputStream.setInputArray(inputArray); inputStream.setAdvancedColumnSelector("1-3"); //inputStream.addPlugIn(new ShufflePlugin()); /* The first InputConnector containing the training data */ InputConnector input1 = new InputConnector(); input1.setInputSynapse(inputStream); // The first two columns contain the input values input1.setAdvancedColumnSelector("1,2"); //input1.setBuffered(true); // By default it's false input.addInputSynapse(input1); /* The second InputConnector containing the desired data */ InputConnector input2 = new InputConnector(); input2.setInputSynapse(inputStream); // The last column contains the desired values input2.setAdvancedColumnSelector("3"); //input2.setBuffered(true); // By default it's false TeachingSynapse trainer = new TeachingSynapse(); trainer.setDesired(input2); // Connects the Teacher to the last layer of the net output.addOutputSynapse(trainer); NeuralNet nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); // Gets the Monitor object and set the learning parameters Monitor monitor = nnet.getMonitor(); monitor.setLearningRate(0.8); monitor.setMomentum(0.3); monitor.setTrainingPatterns(4); // # of rows (patterns) contained in the input file monitor.setTotCicles(2000); // How many times the net must be trained on the input patterns monitor.setLearning(true); // The net must be trained // The application registers itself as monitor's listener so it can receive // the notifications of termination from the net. monitor.addNeuralNetListener(this); mills = System.currentTimeMillis(); nnet.go(); // The net starts the training job } /** * Method declaration */ public void netStopped(NeuralNetEvent e) { long delay = System.currentTimeMillis() - mills; System.out.println("Training finished after "+delay+" ms"); System.exit(0); } /** * Method declaration */ public void cicleTerminated(NeuralNetEvent e) { } /** * Method declaration */ public void netStarted(NeuralNetEvent e) { System.out.println("Training..."); } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor) e.getSource(); long c = mon.getCurrentCicle(); // We want to print the results every 200 epochs if ((c % 200) == 0) { System.out.println(c + " epochs remaining - RMSE = " + mon.getGlobalError()); } } public void netStoppedError(NeuralNetEvent e,String error) { } } /*--- formatting done in "JMRA based on Sun Java Convention" style on 05-08-2002 ---*/
Java
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ /* * JOONE - Java Object Oriented Neural Engine * http://joone.sourceforge.net * * XORMemory.java * */ package org.joone.samples.engine.xor; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.io.*; import org.joone.net.*; import java.util.Vector; /** * Sample class to demostrate the use of the MemoryInputSynapse * * @author Jos�?Rodriguez */ public class XOR_using_NeuralNet_RPROP implements NeuralNetListener { private NeuralNet nnet = null; private MemoryInputSynapse inputSynapse, desiredOutputSynapse; private MemoryOutputSynapse outputSynapse; // XOR input private double[][] inputArray = new double[][] { {0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 1.0} }; // XOR desired output private double[][] desiredOutputArray = new double[][] { {0.0}, {1.0}, {1.0}, {0.0} }; /** * @param args the command line arguments */ public static void main(String args[]) { XOR_using_NeuralNet_RPROP xor = new XOR_using_NeuralNet_RPROP(); xor.initNeuralNet(); xor.train(); } /** * Method declaration */ public void train() { // set the inputs inputSynapse.setInputArray(inputArray); inputSynapse.setAdvancedColumnSelector("1,2"); // set the desired outputs desiredOutputSynapse.setInputArray(desiredOutputArray); desiredOutputSynapse.setAdvancedColumnSelector("1"); // get the monitor object to train or feed forward Monitor monitor = nnet.getMonitor(); // set the monitor parameters monitor.setLearningRate(1); // RPROP needs a positive LR, because // ExtendableLearner multiplies the gradient with the LR before passing // it to the RpropExtender. RPROP only looks at the sign of the gradient // so as long as the lR is positive, RPROP works correctly. monitor.setTrainingPatterns(inputArray.length); monitor.setTotCicles(500); // RPROP parameters monitor.addLearner(0, "org.joone.engine.RpropLearner"); monitor.setBatchSize(monitor.getTrainingPatterns()); monitor.setLearningMode(0); monitor.setLearning(true); nnet.addNeuralNetListener(this); nnet.go(); } /** * Method declaration */ protected void initNeuralNet() { // First create the three layers LinearLayer input = new LinearLayer(); SigmoidLayer hidden = new SigmoidLayer(); SigmoidLayer output = new SigmoidLayer(); // set the dimensions of the layers input.setRows(2); hidden.setRows(3); output.setRows(1); // Now create the two Synapses FullSynapse synapse_IH = new FullSynapse(); /* input -> hidden conn. */ FullSynapse synapse_HO = new FullSynapse(); /* hidden -> output conn. */ // Connect the input layer whit the hidden layer input.addOutputSynapse(synapse_IH); hidden.addInputSynapse(synapse_IH); // Connect the hidden layer whit the output layer hidden.addOutputSynapse(synapse_HO); output.addInputSynapse(synapse_HO); // the input to the neural net inputSynapse = new MemoryInputSynapse(); input.addInputSynapse(inputSynapse); // the output of the neural net outputSynapse = new MemoryOutputSynapse(); output.addOutputSynapse(outputSynapse); // The Trainer and its desired output desiredOutputSynapse = new MemoryInputSynapse(); TeachingSynapse trainer = new TeachingSynapse(); trainer.setDesired(desiredOutputSynapse); // Now we add this structure to a NeuralNet object nnet = new NeuralNet(); nnet.addLayer(input, NeuralNet.INPUT_LAYER); nnet.addLayer(hidden, NeuralNet.HIDDEN_LAYER); nnet.addLayer(output, NeuralNet.OUTPUT_LAYER); nnet.setTeacher(trainer); output.addOutputSynapse(trainer); } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); if (mon.getCurrentCicle() % 100 == 0) System.out.println("Epoch: "+(mon.getTotCicles()-mon.getCurrentCicle())+" RMSE:"+mon.getGlobalError()); } public void netStarted(NeuralNetEvent e) { } public void netStopped(NeuralNetEvent e) { Monitor mon = (Monitor)e.getSource(); // Read the last pattern and print it out Vector patts = outputSynapse.getAllPatterns(); Pattern pattern = (Pattern)patts.elementAt(patts.size() - 1); System.out.println("Output Pattern = " + pattern.getArray()[0] + " Error: " + mon.getGlobalError()); } public void netStoppedError(NeuralNetEvent e, String error) { } } /*--- formatting done in "JMRA based on Sun Java Convention" style on 05-25-2002 ---*/
Java
/* * EmbeddedXOR.java * * Created on 7 maggio 2002, 19.27 */ package org.joone.samples.engine.xor; import org.joone.log.*; import org.joone.engine.*; import org.joone.net.NeuralNet; import java.io.*; /** * This example shows the use of a neural network embedded in another * application that gets the output from the DirectSynapse object * querying the neural network with one input pattern at time * * @author pmarrone */ public class ImmediateEmbeddedXOR { /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(ImmediateEmbeddedXOR.class); private double[][] inputArray = { {0, 0}, {0, 1}, {1, 0}, {1, 1} }; private static String xorNet = "org/joone/samples/engine/xor/xor.snet"; /** Creates a new instance of EmbeddedXOR */ public ImmediateEmbeddedXOR() { } /** * @param args the command line arguments */ public static void main(String[] args) { ImmediateEmbeddedXOR xor = new ImmediateEmbeddedXOR(); xor.Go(xorNet); } private void Go(String fileName) { // We load the serialized XOR neural net NeuralNet xor = restoreNeuralNet(fileName); if (xor != null) { /* We get the first layer of the net (the input layer), then remove all the input synapses attached to it. */ Layer input = xor.getInputLayer(); input.removeAllInputs(); /* We get the last layer of the net (the output layer), then remove all the output synapses attached to it and attach a DirectSynapse */ Layer output = xor.getOutputLayer(); output.removeAllOutputs(); DirectSynapse memOut = new DirectSynapse(); output.addOutputSynapse(memOut); // Now we interrogate the net /* Note: because we use nnet.singleStepForward() to interrogate the network, we don't need any input synapse, nor to invoke nnet.go() */ xor.getMonitor().setLearning(false); for (int n=0; n < 100; ++n) { log.debug("Launch #"+n); for (int i=0; i < 4; ++i) { // Prepare the next input pattern Pattern iPattern = new Pattern(inputArray[i]); iPattern.setCount(i+1); // Interrogate the net //xor.singleStepForward(iPattern); // Read the output pattern and print out it Pattern pattern = memOut.fwdGet(); log.debug("Output Pattern #"+(i+1)+" = "+pattern.getArray()[0]); } } log.debug("Finished"); } } // // TO DO // add some comments private NeuralNet restoreNeuralNet(String fileName) { NeuralNet nnet = null; try { FileInputStream stream = new FileInputStream(fileName); ObjectInput input = new ObjectInputStream(stream); nnet = (NeuralNet)input.readObject(); } catch (Exception e) { log.warn( "Exception thrown while restoring the Neural Net. Message is : " + e.getMessage(), e ); } return nnet; } }
Java
/* * XORTrainer.java * * Created on 3 marzo 2004, 17.26 */ package org.joone.samples.engine.xor; import org.joone.engine.*; import org.joone.net.*; import org.joone.io.*; import java.io.*; import java.util.*; /** * This sample application loads a serialized network and launches it in training mode * @author P.Marrone */ public class XORTrainer implements NeuralNetListener { private static String xorNet = "org/joone/samples/engine/xor/xor.snet"; /** Creates a new instance of XORTrainer */ public XORTrainer() { } /** * @param args the command line arguments */ public static void main(String[] args) { XORTrainer xor = new XORTrainer(); xor.Go(xorNet); } private void Go(String fileName) { NeuralNet xor = restoreNeuralNet(fileName); if (xor != null) { xor.getMonitor().addNeuralNetListener(this); xor.getMonitor().setLearning(true); TreeSet tree = xor.check(); if (tree.isEmpty()) { xor.go(true); System.out.println("Network stopped. Last RMSE="+xor.getMonitor().getGlobalError()); } else { Iterator it = tree.iterator(); while (it.hasNext()) { NetCheck nc = (NetCheck)it.next(); System.out.println(nc.toString()); } } } } private NeuralNet restoreNeuralNet(String fileName) { NeuralNet nnet = null; try { FileInputStream stream = new FileInputStream(fileName); ObjectInput input = new ObjectInputStream(stream); nnet = (NeuralNet)input.readObject(); } catch (Exception e) { System.out.println( "Exception was thrown. Message is : " + e.getMessage()); } return nnet; } public void cicleTerminated(NeuralNetEvent e) { } public void errorChanged(NeuralNetEvent e) { Monitor mon = (Monitor) e.getSource(); long c = mon.getCurrentCicle(); // We want to print the results every 200 cycles if (c % 200 == 0) { System.out.println(c + " epochs remaining - RMSE = " + mon.getGlobalError()); } } public void netStarted(NeuralNetEvent e) { System.out.println("Started..."); } public void netStopped(NeuralNetEvent e) { System.out.println("Stopped..."); } public void netStoppedError(NeuralNetEvent e, String error) { System.out.println("Error: "+error); System.exit(1); } }
Java
/* * ValidationSample.java * * Created on 11 november 2002, 22.59 * @author pmarrone */ package org.joone.samples.engine.scripting; import org.joone.engine.*; import org.joone.engine.learning.*; import org.joone.net.*; import org.joone.io.*; import org.joone.util.*; import java.io.*; /** * This example shows how to use the joone's scripting engine to * to check the training level of the net using a validation * data source. * In this example we will learn to use the following objects: * - org.joone.util.LearningSwitch * - org.joone.util.MacroPlugin * - org.joone.util.NormalizerPlugIn * * This program shows how to build the same neural net contained into the * org/joone/samples/editor/scripting/ValidationSample.ser file using * only java code and the core engine's API. Open that net in * the GUI editor to see the architecture of the net built in this example. */ public class ScriptValidationSample { NeuralNet net; private static String filePath = "org/joone/samples/engine/scripting"; /** Creates a new instance of SampleScript */ public ScriptValidationSample() { } /** * @param args the command line arguments */ public static void main(String[] args) { ScriptValidationSample sampleNet = new ScriptValidationSample(); sampleNet.initialize(filePath); sampleNet.start(); } private void initialize(String path) { /* Creates the three layers and connect them */ LinearLayer ILayer = new LinearLayer(); // Input Layer SigmoidLayer HLayer = new SigmoidLayer(); // Hidden Layer SigmoidLayer OLayer = new SigmoidLayer(); // Output Layer ILayer.setRows(13); // The input pattern has 13 columns HLayer.setRows(4); OLayer.setRows(1); // The desired pattern has 1 column FullSynapse synIH = new FullSynapse(); FullSynapse synHO = new FullSynapse(); this.connect(ILayer, synIH, HLayer); this.connect(HLayer, synHO, OLayer); /* Creates all the required input data sets */ FileInputSynapse ITdata = this.createInput(path+"/wine.txt",1,2,14); /* The input training data set */ FileInputSynapse IVdata = this.createInput(path+"/wine.txt",131,2,14); /* The input validation data set */ FileInputSynapse DTdata = this.createInput(path+"/wine.txt",1,1,1); /* The desired training data set */ FileInputSynapse DVdata = this.createInput(path+"/wine.txt",131,1,1); /* The desired validation data set */ /* Creates and attach the input learning switch */ LearningSwitch Ilsw = this.createSwitch(ITdata, IVdata); ILayer.addInputSynapse(Ilsw); /* Creates and attach the desired learning switch */ LearningSwitch Dlsw = this.createSwitch(DTdata, DVdata); TeachingSynapse ts = new TeachingSynapse(); // The teacher of the net ts.setDesired(Dlsw); OLayer.addOutputSynapse(ts); /* Now we put all togheter into a NeuralNet object */ net = new NeuralNet(); net.addLayer(ILayer, NeuralNet.INPUT_LAYER); net.addLayer(HLayer, NeuralNet.HIDDEN_LAYER); net.addLayer(OLayer, NeuralNet.OUTPUT_LAYER); net.setTeacher(ts); /* Reads and inserts the text of the validation macro */ MacroPlugin mPlugin = new MacroPlugin(); String validation = this.readFile(new File(path+"/validation.bsh")); mPlugin.getMacroManager().addMacro("cycleTerminated", validation); /* Sets the scripting */ mPlugin.setRate(100); // Prints out the results each 100 cycles net.setMacroPlugin(mPlugin); net.setScriptingEnabled(true); // Enables the scripts' execution /* Sets the Monitor's parameters */ Monitor mon = net.getMonitor(); mon.setLearningRate(0.2); mon.setMomentum(0.3); /* Here we set at the beginning the number of the training rows, * because the number of the validation rows is set by the script * at the validation time */ mon.setTrainingPatterns(130); mon.setValidationPatterns(48); mon.setTotCicles(1000); mon.setLearning(true); } /** Creates a FileInputSynapse */ private FileInputSynapse createInput(String name, int firstRow, int firstCol, int lastCol) { FileInputSynapse input = new FileInputSynapse(); input.setInputFile(new File(name)); input.setFirstRow(firstRow); if (firstCol != lastCol) input.setAdvancedColumnSelector(firstCol+"-"+lastCol); else input.setAdvancedColumnSelector(Integer.toString(firstCol)); // We normalize the input data in the range 0 - 1 NormalizerPlugIn norm = new NormalizerPlugIn(); if (firstCol != lastCol) norm.setAdvancedSerieSelector("1-"+Integer.toString(lastCol-firstCol+1)); else norm.setAdvancedSerieSelector("1"); input.addPlugIn(norm); return input; } /** Connects two Layers with a Synapse */ private void connect(Layer ly1, Synapse syn, Layer ly2) { ly1.addOutputSynapse(syn); ly2.addInputSynapse(syn); } /* Creates a LearningSwitch and attach to it both the training and the desired input synapses */ private LearningSwitch createSwitch(StreamInputSynapse IT, StreamInputSynapse IV) { LearningSwitch lsw = new LearningSwitch(); lsw.addTrainingSet(IT); lsw.addValidationSet(IV); return lsw; } /** * Reads the content of the file. * * @param p_file the content of the file that is to be read. * @return the content of the file. */ private String readFile(File p_file) { String str = null, msg; FileReader reader = null; try { reader = new FileReader(p_file); int tch = new Long(p_file.length()).intValue(); char[] m_buf = new char[tch]; int nch = reader.read(m_buf); if (nch != -1) str = new String(m_buf, 0, nch); reader.close(); } catch (FileNotFoundException fnfe) { System.err.println(fnfe.getMessage()); return str; } catch (IOException ioe) { System.err.println(ioe.getMessage()); } return str; } private void start() { net.go(); } }
Java
/* * ParityInputSynapse.java * * Created on November 28, 2004, 4:24 PM */ package org.joone.samples.util; import org.joone.exception.JooneRuntimeException; import org.joone.io.*; import org.joone.log.*; /** * <p>This synapse creates input data (which is also the desired output data) for * the Encoder problem. * The encoder problem is the problem consisting of N patterns (each pattern also * consists of N bits). Each pattern has only one bit turned on (1) and all the other * bits are off (0). The task is to duplicate the input units into the output units, * going through (usually a smaller) hidden layer. * * <p>This class is also mainly created to test new techniques. * * @author Boris Jansen */ public class EncoderInputSynapse extends StreamInputSynapse { /** Logger */ private static final ILogger log = LoggerFactory.getLogger(EncoderInputSynapse.class); /** The size of the encoder problem, that is, number of patterns and also at the same * time the number of bits each pattern consists of. */ private int size = 0; // default /** The value for the upper bit. */ private double upperBit = 1.0; // default /** The value for the lower bit. */ private double lowerBit = 0.0; // default /** Creates a new instance of EncoderInputSynapse. */ public EncoderInputSynapse() { } /** Creates a new instance of EncoderInputSynapse. */ public EncoderInputSynapse(double aLowerBit, double anUpperBit) { lowerBit = aLowerBit; upperBit = anUpperBit; } protected void initInputStream() throws JooneRuntimeException { setAdvancedColumnSelector("1-" + size); setTokens(new MemoryInputTokenizer(createEncoderArray())); } /** * Sets the number of bits for each pattern. This value is also at the same time the number * of patterns. * * @param aSize the size, number of bits for each pattern and also the number of patterns itself. */ public void setSize(int aSize) { size = aSize; } /** * Gets the size, that is, the number of bits of the input pattern and at the same time * the number of patterns itself. * * @return the size. */ public int getSize() { return size; } /** * Gets the number of patterns that exist for the parity problem. * * @return the number of patterns that exist. * @see {@link:getSize()} */ public int getNumOfPatterns() { return size; } /** * Creates an array holding the input (which are also the desired output patterns) * patterns for the encoder problem. * * @return an array holding an instance of the encoder problem. */ protected double[][] createEncoderArray() { int myPatterns = getNumOfPatterns(); double[][] myInstance = new double[myPatterns][getSize()]; for(int i = 0; i < myPatterns; i++) { for(int j = 0; j < getSize(); j++) { myInstance[i][j] = getLowerBit(); } myInstance[i][i] = getUpperBit(); } /* debug for(int i = 0; i < myInstance.length; i++) { String myText = ""; for(int j = 0; j < myInstance[i].length; j++) { myText += myInstance[i][j] + " "; } log.debug(myText); } end debug */ return myInstance; } /** * Sets the value for the upper bit. * * @param aValue the value to use for the upper bit. */ public void setUpperBit(double aValue) { upperBit = aValue; } /** * Gets the value used for the upper bit. * * @returns the value used for the upper bit. */ public double getUpperBit() { return upperBit; } /** * Sets the value for the lower bit. * * @param aValue the value to use for the lower bit. */ public void setLowerBit(double aValue) { lowerBit = aValue; } /** * Gets the value used for the lower bit. * * @returns the value used for the lower bit. */ public double getLowerBit() { return lowerBit; } }
Java
/* * ParityInputSynapse.java * * Created on November 28, 2004, 4:24 PM */ package org.joone.samples.util; import org.joone.exception.JooneRuntimeException; import org.joone.io.*; import org.joone.log.*; /** * <p>This synapse creates input and desired output data for the parity problem. * The parity problem is the problem where numbers (in binary form) having an even * number of ones should output a zero and numbers having an odd number of ones * should output a one. * <p>The partity problem is a problem that is often used to test new learning * algorithms, etc., because the problem is quite difficult. Whenever one bit * changes the output should be the opposite. * <p>This class is also mainly created to test new techniques. * <p>The default size of the parity problem is two, that is, it creates the training * data for the XOR problem. * * @author Boris Jansen */ public class ParityInputSynapse extends StreamInputSynapse { /** Logger */ private static final ILogger log = LoggerFactory.getLogger(ParityInputSynapse.class); /** The size of the parity problem, that is, the number of bits for the input data. The default is 2, which is just the XOR problem. */ private int paritySize = 2; // default /** The value for the upper bit. */ private double upperBit = 1.0; // default /** The value for the lower bit. */ private double lowerBit = 0.0; // default /** Creates a new instance of ParityInputSynapse */ public ParityInputSynapse() { } protected void initInputStream() throws JooneRuntimeException { setAdvancedColumnSelector("1-" + (paritySize + 1)); setTokens(new MemoryInputTokenizer(createParityArray())); } /** * Sets the number of bits the parity problem should consist of, that is, the number * of bits the input should consist of. For example, a size 2, is the XOR problem. * * @param aSize the size / number of bits for the input. */ public void setParitySize(int aSize) { paritySize = aSize; } /** * Gets the parity size, that is, the number of bits of the input pattern. * * @return the parity size. */ public int getParitySize() { return paritySize; } /** * Gets the number of patterns that exist for the parity problem, that is * <code>2^parity-size</code>. * * @return the number of patterns that exist for the parity problem based on the * parity size. */ public int getNumOfPatterns() { return (int)Math.pow(2, paritySize); } /** * Creates an array holding the input and desired output values for the parity problem. * * @return an array holding an instance of the parity problem. */ protected double[][] createParityArray() { int myPatterns = getNumOfPatterns(); int myDesiredOutput, myBit, myTemp; double[][] myParityInstance = new double[myPatterns][paritySize + 1]; for(int i = 0; i < myPatterns; i++) { myDesiredOutput = 0; myTemp = i; for(int j = 0; j < paritySize; j++) { myBit = myTemp % 2; myTemp = myTemp / 2; if(myBit == 1) { myDesiredOutput = (myDesiredOutput + 1) % 2; } if(myBit == 0) { myParityInstance[i][j] = getLowerBit(); } else { myParityInstance[i][j] = getUpperBit(); } } if(myDesiredOutput == 0) { myParityInstance[i][paritySize] = getLowerBit(); } else { myParityInstance[i][paritySize] = getUpperBit(); } } /* debug for(int i = 0; i < myParityInstance.length; i++) { String myText = ""; for(int j = 0; j < myParityInstance[i].length; j++) { myText += myParityInstance[i][j] + " "; } log.debug(myText); } // end debug */ return myParityInstance; } /** * Sets the value for the upper bit. * * @param aValue the value to use for the upper bit. */ public void setUpperBit(double aValue) { upperBit = aValue; } /** * Gets the value used for the upper bit. * * @returns the value used for the upper bit. */ public double getUpperBit() { return upperBit; } /** * Sets the value for the lower bit. * * @param aValue the value to use for the lower bit. */ public void setLowerBit(double aValue) { lowerBit = aValue; } /** * Gets the value used for the lower bit. * * @returns the value used for the lower bit. */ public double getLowerBit() { return lowerBit; } }
Java
/* * MemoryInputTokenizer.java * * Created on 7 april 2002, 13.37 */ package org.joone.io; /** * * @author pmarrone */ public class MemoryInputTokenizer implements PatternTokenizer { private double[][] inputArray; private int lineNo = 0; private int mark = 0; private char decimalPoint; /** Creates a new instance of MemoryInputTokenizer */ public MemoryInputTokenizer() { } public MemoryInputTokenizer(double[][] array) { inputArray = array; } /** Go to the last marked position. Begin of input stream if no mark detected. */ public void resetInput() throws java.io.IOException { lineNo = mark; } /** Return the current line number. * @return the current line number */ public int getLineno() { return lineNo; } public char getDecimalPoint() { return decimalPoint; } /** Go to the next line * @return false if EOF, otherwise true * @throws IOException if an I/O Error occurs */ public boolean nextLine() throws java.io.IOException { ++lineNo; if (lineNo > inputArray.length) return false; else return true; } public int getNumTokens() throws java.io.IOException { double[] line = this.getTokensArray(); return line.length; } /** marks the current position. * @throws IOException if an I/O Error occurs */ public void mark() throws java.io.IOException { mark = lineNo; } /** * Returns the value of the token at 'posiz' column of the current line * Creation date: (17/10/2000 0.30.08) * @return float * @param posiz int */ public double getTokenAt(int posiz) throws java.io.IOException { double[] line = this.getTokensArray(); return line[posiz]; } /** * Returns an array of values of the current line * Creation date: (17/10/2000 0.13.45) * @return float[] */ public double[] getTokensArray() { return inputArray[lineNo - 1]; } public void setDecimalPoint(char decimalPoint) { this.decimalPoint = decimalPoint; } }
Java
package org.joone.io; import java.io.*; import java.util.TreeSet; import org.joone.log.*; import org.joone.engine.*; import org.joone.net.NetCheck; import org.apache.poi.poifs.filesystem.*; import org.apache.poi.hssf.usermodel.*; /** This class allows data to be read from an Excel XLS formatted file. The class * requires the specification of a file name and a worksheet name is optional. */ public class XLSOutputSynapse extends StreamOutputSynapse { /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(XLSOutputSynapse.class); /** The serial version ID for this object. */ static final long serialVersionUID = -9167076940131905606L; /** The name of the XLS File to write network output data to. */ private String FileName = ""; /** The stream to be used for writing. */ private transient FileOutputStream o_stream; /** The input stream of an XLS file that already exists. */ private transient FileInputStream i_stream; /** The Internal HSSF sheet to output data to. */ private transient HSSFSheet o_sheet; /** The worksheet index number. */ private int o_sheet_index = -1 ; /** Internal row count. */ private int row_no = 0; /** Starting position when the first pattern being written. */ private int startCol; private int startRow; /** The working copy of the HSSF Workbook used to output data. */ private transient HSSFWorkbook workbook; /** The name of the XLS sheet within the XLS File that will be used to write data * to. */ private String o_sheet_name = new String("j_output"); /** The default constructor for this XLSOutputSynapse. */ public XLSOutputSynapse() { super(); /* Default value. */ startCol = 0; startRow = 0; } /** Write any remaining data to the XLS file. */ public void flush() { try { workbook.write(o_stream); } catch (IOException ioe) { String error = "IOException in "+getName()+". Message is : "; log.warn(error + ioe); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),error + ioe.getMessage()); } } /** Writes a Pattern to the XLS file. * @param pattern The Pattern to write to the XLS file. */ public synchronized void write(Pattern pattern) { if ((workbook == null) || (pattern.getCount() == 1)) { try { this.initOutputStream(); // get handle on workbook } catch (IOException ioe) { String error = "IOException in "+getName()+". Message is : "; log.warn(error + ioe); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),error + ioe.getMessage()); } } if (pattern.getCount() == -1) { //open outstream try { o_stream = new FileOutputStream(FileName); workbook.write(o_stream); o_stream.close(); // close stream to be clean row_no = startRow; // reset count workbook = null; //reset workbook to force reread of file } catch (IOException ioe) { String error = "IOException in "+getName()+". Message is : "; log.warn(error + ioe); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),error + ioe.getMessage()); } } else { HSSFRow row; HSSFCell cell; double[] array = pattern.getArray(); if (o_sheet.getRow(row_no) == null) { row = o_sheet.createRow((short) row_no); } else { row = o_sheet.getRow(row_no); } for (int i = 0; i < array.length; ++i) { if (!(row.getCell((short) (i+startCol)) == null)) { row.removeCell(row.getCell((short) (i+startCol))); //remove original cell // log.debug("Removing " + row_no + "," + (i+startCol)); } cell = row.createCell((short) (i+startCol), 0); // type 0 numeric cell.setCellValue((double) array[i]); } ++row_no; } } /** Returns the XLS file name used by this synapse. * @return The XLS file name used by this synapse to output data to. */ public java.lang.String getFileName() { return FileName; } /** Sets the XLS file name that this synapse should output data to. * @param fn The XLS file name that this synapse should output data to. */ public void setFileName(String fn) { FileName = fn; } /** Initialises the data stream. */ private void initOutputStream() throws IOException { if (new File(FileName).exists()) { i_stream = new FileInputStream(FileName); POIFSFileSystem i_fs = new POIFSFileSystem(i_stream); workbook = new HSSFWorkbook(i_fs); i_stream.close(); // handle on workbook has been attained } else { o_stream = new FileOutputStream(FileName); // generate file for later use workbook = new HSSFWorkbook(); workbook.write(o_stream); // create valid workbook o_stream.close(); // handle on workbook has been attained } o_sheet_index = workbook.getSheetIndex(o_sheet_name); //find valid sheet if (o_sheet_index != -1) { o_sheet = workbook.getSheetAt(o_sheet_index); } else { o_sheet = workbook.createSheet(o_sheet_name); } row_no = startRow; // reset count } /** Sets the sheet name within the XLS file that this synapse should write data to. * @param sheetName The sheet name within the XLS file that this synapse should write data to. */ public void setSheetName(String sheetName) { o_sheet_name = sheetName; } /** Obtains a list of available sheet names from the XLS file. * @return An array of sheet names found with in the XLS file or null if the file has not * been read yet. */ public String[] getAvailableSheetList() { int sheetCount = workbook.getNumberOfSheets(); String[] availableSheetList = null; for (int i = 0; i > sheetCount; i++) { availableSheetList[i] = workbook.getSheetName(i); } return availableSheetList; } /** Gets the name of sheet within the XLS file that data should be written to. * @return The name of sheet within the XLS file that data should be written to. */ public String getSheetName() { return o_sheet_name; } /** Checks and returns any problems found with the settings of this synapse. * @return A TreeSet of problems or errors found with this synapse. */ public TreeSet check() { TreeSet checks = super.check(); if (FileName == null || FileName.trim().equals("")) { checks.add(new NetCheck(NetCheck.FATAL, "File Name not set." , this)); } return checks; } /** Gets the starting row (0 based) of the XLS sheet. * @return Starting row (0 based) of the XLS sheet. */ public int getStartRow(int startRow) { return startRow; } /** Gets the starting col (0 based) of the XLS sheet. * @return Starting col (0 based) of the XLS sheet. */ public int getStartCol(int startCol) { return startCol; } /** Set the starting row (0 based) of the XLS sheet. */ public void setStartRow(int startRow) { this.startRow = startRow; } /** Set the starting col (0 based) of the XLS sheet. */ public void setStartCol(int startCol) { this.startCol = startCol; } }
Java
package org.joone.io; import java.beans.*; public class InputSwitchSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor//GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( org.joone.io.InputSwitchSynapse.class , null ); // NOI18N//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers//GEN-FIRST:Properties private static final int PROPERTY_activeInput = 0; private static final int PROPERTY_advancedColumnSelector = 1; private static final int PROPERTY_allInputs = 2; private static final int PROPERTY_defaultInput = 3; private static final int PROPERTY_monitor = 4; private static final int PROPERTY_name = 5; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[6]; try { properties[PROPERTY_activeInput] = new PropertyDescriptor ( "activeInput", org.joone.io.InputSwitchSynapse.class, "getActiveInput", "setActiveInput" ); // NOI18N properties[PROPERTY_advancedColumnSelector] = new PropertyDescriptor ( "advancedColumnSelector", org.joone.io.InputSwitchSynapse.class, "getAdvancedColumnSelector", "setAdvancedColumnSelector" ); // NOI18N properties[PROPERTY_advancedColumnSelector].setHidden ( true ); properties[PROPERTY_allInputs] = new PropertyDescriptor ( "allInputs", org.joone.io.InputSwitchSynapse.class, "getAllInputs", "setAllInputs" ); // NOI18N properties[PROPERTY_allInputs].setExpert ( true ); properties[PROPERTY_defaultInput] = new PropertyDescriptor ( "defaultInput", org.joone.io.InputSwitchSynapse.class, "getDefaultInput", "setDefaultInput" ); // NOI18N properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", org.joone.io.InputSwitchSynapse.class, "getMonitor", "setMonitor" ); // NOI18N properties[PROPERTY_monitor].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", org.joone.io.InputSwitchSynapse.class, "getName", "setName" ); // NOI18N } catch(IntrospectionException e) { e.printStackTrace(); }//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers//GEN-FIRST:Methods private static final int METHOD_addInputSynapse0 = 0; private static final int METHOD_addNoise1 = 1; private static final int METHOD_canCountSteps2 = 2; private static final int METHOD_check3 = 3; private static final int METHOD_fwdGet4 = 4; private static final int METHOD_fwdPut5 = 5; private static final int METHOD_gotoFirstLine6 = 6; private static final int METHOD_gotoLine7 = 7; private static final int METHOD_randomize8 = 8; private static final int METHOD_readAll9 = 9; private static final int METHOD_removeAllInputs10 = 10; private static final int METHOD_removeInputSynapse11 = 11; private static final int METHOD_reset12 = 12; private static final int METHOD_resetInput13 = 13; private static final int METHOD_revGet14 = 14; private static final int METHOD_revPut15 = 15; // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[16]; try { methods[METHOD_addInputSynapse0] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("addInputSynapse", new Class[] {org.joone.io.StreamInputSynapse.class})); // NOI18N methods[METHOD_addInputSynapse0].setDisplayName ( "" ); methods[METHOD_addNoise1] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("addNoise", new Class[] {Double.TYPE})); // NOI18N methods[METHOD_addNoise1].setDisplayName ( "" ); methods[METHOD_canCountSteps2] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("canCountSteps", new Class[] {})); // NOI18N methods[METHOD_canCountSteps2].setDisplayName ( "" ); methods[METHOD_check3] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("check", new Class[] {})); // NOI18N methods[METHOD_check3].setDisplayName ( "" ); methods[METHOD_fwdGet4] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("fwdGet", new Class[] {})); // NOI18N methods[METHOD_fwdGet4].setDisplayName ( "" ); methods[METHOD_fwdPut5] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("fwdPut", new Class[] {org.joone.engine.Pattern.class})); // NOI18N methods[METHOD_fwdPut5].setDisplayName ( "" ); methods[METHOD_gotoFirstLine6] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("gotoFirstLine", new Class[] {})); // NOI18N methods[METHOD_gotoFirstLine6].setDisplayName ( "" ); methods[METHOD_gotoLine7] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("gotoLine", new Class[] {Integer.TYPE})); // NOI18N methods[METHOD_gotoLine7].setDisplayName ( "" ); methods[METHOD_randomize8] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("randomize", new Class[] {Double.TYPE})); // NOI18N methods[METHOD_randomize8].setDisplayName ( "" ); methods[METHOD_readAll9] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("readAll", new Class[] {})); // NOI18N methods[METHOD_readAll9].setDisplayName ( "" ); methods[METHOD_removeAllInputs10] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("removeAllInputs", new Class[] {})); // NOI18N methods[METHOD_removeAllInputs10].setDisplayName ( "" ); methods[METHOD_removeInputSynapse11] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("removeInputSynapse", new Class[] {java.lang.String.class})); // NOI18N methods[METHOD_removeInputSynapse11].setDisplayName ( "" ); methods[METHOD_reset12] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("reset", new Class[] {})); // NOI18N methods[METHOD_reset12].setDisplayName ( "" ); methods[METHOD_resetInput13] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("resetInput", new Class[] {})); // NOI18N methods[METHOD_resetInput13].setDisplayName ( "" ); methods[METHOD_revGet14] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("revGet", new Class[] {})); // NOI18N methods[METHOD_revGet14].setDisplayName ( "" ); methods[METHOD_revPut15] = new MethodDescriptor ( org.joone.io.InputSwitchSynapse.class.getMethod("revPut", new Class[] {org.joone.engine.Pattern.class})); // NOI18N methods[METHOD_revPut15].setDisplayName ( "" ); } catch( Exception e) {}//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.io.*; import java.util.TreeSet; import org.joone.log.*; import org.joone.engine.*; import org.joone.net.NetCheck; public class FileOutputSynapse extends StreamOutputSynapse { /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(FileOutputSynapse.class); private String FileName = ""; private boolean append = false; // The default printer protected transient PrintWriter printer = null; private static final long serialVersionUID = 3194671306693862830L; public FileOutputSynapse() { super(); } /** * * Writes to the printer object. */ public synchronized void write(Pattern pattern) { if ((printer == null) || (pattern.getCount() == 1)) setFileName(FileName); if (pattern.getCount() == -1) { flush(); } else { double[] array = pattern.getArray(); for (int i=0; i < array.length; ++i) { printer.print(array[i]); if (i < (array.length - 1)) printer.print(getSeparator()); } printer.println(); //printer.flush(); // Flush the output after every line, avoid building any large buffers } // End else } /** * Inserire qui la descrizione del metodo. * Data di creazione: (23/04/00 0.58.30) * @return java.lang.String */ public java.lang.String getFileName() { return FileName; } public void setFileName(String fn) { FileName = fn; try { if (printer != null) printer.close(); printer = new PrintWriter(new FileOutputStream(fn, isAppend()), true); } catch (IOException ioe) { String error = "IOException in "+getName()+". Message is : "; log.error(error + ioe.getMessage()); if ( getMonitor() != null) new NetErrorManager(getMonitor(),error+ioe.getMessage()); } } public void flush() { printer.flush(); printer.close(); printer=null; } public TreeSet check() { TreeSet checks = super.check(); if (FileName == null || FileName.trim().equals("")) { checks.add(new NetCheck(NetCheck.FATAL, "File Name not set." , this)); } return checks; } /** Getter for property append. * @return Value of property append. * */ public boolean isAppend() { return append; } /** Setter for property append. * @param append if <code>true</code>, then bytes will be written * to the end of the file rather than the beginning * */ public void setAppend(boolean append) { this.append = append; } }
Java
package org.joone.io; import java.io.*; import java.util.TreeSet; import org.joone.log.*; import org.joone.net.NetCheck; import org.joone.exception.JooneRuntimeException; import org.joone.engine.NetErrorManager; /** Allows data to be presented to the network from a file. The file must contain * semi-colon seperated values e.g '2;5;7;2.1'. */ public class FileInputSynapse extends StreamInputSynapse { /** The logger used to log errors and warnings. */ private static final ILogger log = LoggerFactory.getLogger(FileInputSynapse.class); private static final long serialVersionUID = 7456627292136514416L; /** The name of the file to extract information from. */ private String fileName = ""; private transient File inputFile; public FileInputSynapse() { super(); } /** Gets the file name that this synapse uses to extract the input data from. * @return The file name that this synapse uses to extract the input data from. * @deprecated use getInputFile instead */ public java.lang.String getFileName() { return fileName; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { super.readObjectBase(in); if (in.getClass().getName().indexOf("xstream") == -1) { fileName = (String) in.readObject(); } if ((fileName != null) && (fileName.length() > 0)) inputFile = new File(fileName); } /** Sets the file name that this synapse should extract data from. * @param newFileName The file name that this synapse should extract data from. * @deprecated use setInputFile instead */ public void setFileName(java.lang.String newFileName) { if (!fileName.equals(newFileName)) { fileName = newFileName; this.resetInput(); super.setTokens(null); //initInputStream(); } } private void writeObject(ObjectOutputStream out) throws IOException { super.writeObjectBase(out); if (out.getClass().getName().indexOf("xstream") == -1) { out.writeObject(fileName); } } protected void initInputStream() throws JooneRuntimeException { if ((fileName != null) && (!fileName.equals(new String("")))) { try { inputFile = new File(fileName); FileInputStream fis = new FileInputStream(inputFile); StreamInputTokenizer sit; if (getMaxBufSize() > 0) sit = new StreamInputTokenizer(new InputStreamReader(fis), getMaxBufSize()); else sit = new StreamInputTokenizer(new InputStreamReader(fis)); super.setTokens(sit); } catch (IOException ioe) { String error = "IOException in "+getName()+". Message is : "; log.warn(error + ioe.getMessage()); if ( getMonitor() != null) new NetErrorManager(getMonitor(),error+ioe.getMessage()); } } } /** Returns a TreeSet of errors or problems regarding the setup of this synapse. * @return A TreeSet of errors or problems regarding the setup of this synapse. */ public TreeSet check() { TreeSet checks = super.check(); if (fileName == null || fileName.trim().equals("")) { checks.add(new NetCheck(NetCheck.FATAL, "File Name not set." , this)); } else { if (!getInputFile().exists()) { NetCheck error = new NetCheck(NetCheck.WARNING, "Input File doesn't exist." , this); if (getInputPatterns().isEmpty()) error.setSeverity(NetCheck.FATAL); checks.add(error); } } return checks; } public File getInputFile() { return inputFile; } public void setInputFile(File inputFile) { if (inputFile != null) { if (!fileName.equals(inputFile.getAbsolutePath())) { this.inputFile = inputFile; fileName = inputFile.getAbsolutePath(); this.resetInput(); super.setTokens(null); } } else { this.inputFile = inputFile; fileName = ""; this.resetInput(); super.setTokens(null); } } }
Java
/* * InputConnectorBeanInfo.java * * Created on September 21, 2004, 3:09 PM */ package org.joone.io; import java.beans.*; /** * @author drmarpao */ public class InputConnectorBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( InputConnector.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedColumnSelector = 0; private static final int PROPERTY_buffered = 1; private static final int PROPERTY_enabled = 2; private static final int PROPERTY_firstRow = 3; private static final int PROPERTY_lastRow = 4; private static final int PROPERTY_name = 5; private static final int PROPERTY_stepCounter = 6; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[7]; try { properties[PROPERTY_advancedColumnSelector] = new PropertyDescriptor ( "advancedColumnSelector", InputConnector.class, "getAdvancedColumnSelector", "setAdvancedColumnSelector" ); properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", InputConnector.class, "isBuffered", "setBuffered" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", InputConnector.class, "isEnabled", "setEnabled" ); properties[PROPERTY_firstRow] = new PropertyDescriptor ( "firstRow", InputConnector.class, "getFirstRow", "setFirstRow" ); properties[PROPERTY_lastRow] = new PropertyDescriptor ( "lastRow", InputConnector.class, "getLastRow", "setLastRow" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", InputConnector.class, "getName", "setName" ); properties[PROPERTY_stepCounter] = new PropertyDescriptor ( "stepCounter", InputConnector.class, "isStepCounter", "setStepCounter" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods private static final int METHOD_addNoise0 = 0; private static final int METHOD_canCountSteps1 = 1; private static final int METHOD_check2 = 2; private static final int METHOD_fwdGet3 = 3; private static final int METHOD_fwdPut4 = 4; private static final int METHOD_gotoFirstLine5 = 5; private static final int METHOD_gotoLine6 = 6; private static final int METHOD_initLearner7 = 7; private static final int METHOD_InspectableTitle8 = 8; private static final int METHOD_Inspections9 = 9; private static final int METHOD_numColumns10 = 10; private static final int METHOD_randomize11 = 11; private static final int METHOD_readAll12 = 12; private static final int METHOD_reset13 = 13; private static final int METHOD_resetInput14 = 14; private static final int METHOD_revGet15 = 15; private static final int METHOD_revPut16 = 16; private static final int METHOD_setPlugin17 = 17; // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[18]; try { methods[METHOD_addNoise0] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("addNoise", new Class[] {Double.TYPE})); methods[METHOD_addNoise0].setDisplayName ( "" ); methods[METHOD_canCountSteps1] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("canCountSteps", new Class[] {})); methods[METHOD_canCountSteps1].setDisplayName ( "" ); methods[METHOD_check2] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("check", new Class[] {})); methods[METHOD_check2].setDisplayName ( "" ); methods[METHOD_fwdGet3] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("fwdGet", new Class[] {})); methods[METHOD_fwdGet3].setDisplayName ( "" ); methods[METHOD_fwdPut4] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("fwdPut", new Class[] {org.joone.engine.Pattern.class})); methods[METHOD_fwdPut4].setDisplayName ( "" ); methods[METHOD_gotoFirstLine5] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("gotoFirstLine", new Class[] {})); methods[METHOD_gotoFirstLine5].setDisplayName ( "" ); methods[METHOD_gotoLine6] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("gotoLine", new Class[] {Integer.TYPE})); methods[METHOD_gotoLine6].setDisplayName ( "" ); methods[METHOD_initLearner7] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("initLearner", new Class[] {})); methods[METHOD_initLearner7].setDisplayName ( "" ); methods[METHOD_InspectableTitle8] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("InspectableTitle", new Class[] {})); methods[METHOD_InspectableTitle8].setDisplayName ( "" ); methods[METHOD_Inspections9] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("Inspections", new Class[] {})); methods[METHOD_Inspections9].setDisplayName ( "" ); methods[METHOD_numColumns10] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("numColumns", new Class[] {})); methods[METHOD_numColumns10].setDisplayName ( "" ); methods[METHOD_randomize11] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("randomize", new Class[] {Double.TYPE})); methods[METHOD_randomize11].setDisplayName ( "" ); methods[METHOD_readAll12] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("readAll", new Class[] {})); methods[METHOD_readAll12].setDisplayName ( "" ); methods[METHOD_reset13] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("reset", new Class[] {})); methods[METHOD_reset13].setDisplayName ( "" ); methods[METHOD_resetInput14] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("resetInput", new Class[] {})); methods[METHOD_resetInput14].setDisplayName ( "" ); methods[METHOD_revGet15] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("revGet", new Class[] {})); methods[METHOD_revGet15].setDisplayName ( "" ); methods[METHOD_revPut16] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("revPut", new Class[] {org.joone.engine.Pattern.class})); methods[METHOD_revPut16].setDisplayName ( "" ); methods[METHOD_setPlugin17] = new MethodDescriptor ( org.joone.io.InputConnector.class.getMethod("setPlugin", new Class[] {org.joone.util.ConverterPlugIn.class})); methods[METHOD_setPlugin17].setDisplayName ( "" ); } catch( Exception e) {}//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
/* * MultipleInputSynapse.java * * Created on 10 gennaio 2005, 21.23 */ package org.joone.io; import java.io.IOException; import org.joone.engine.*; /** * This class reads sequentially all the connected input synapses, * in order to be able to use multiple sources as inputs. * It reads all the rows of the first input synapse, then all the * rows of the second one, and so on. The Stop Pattern is injected * only after the last row of the last input synapse is read. * * When this class is used, the monitor.trainingPatterns must be set * to the sum of the rows of all the attached input synapses. * * @author P.Marrone */ public class MultipleInputSynapse extends InputSwitchSynapse { private int currentInput = 0; private int currentPatt = 0; /** Creates a new instance of MultipleInputSynapse */ public MultipleInputSynapse() { super(); } public Pattern fwdGet() { super.setActiveSynapse((StreamInputSynapse)inputs.get(currentInput)); Pattern patt = super.fwdGet(); return elaboratePattern(patt); } public Pattern fwdGet(InputConnector conn) { StreamInputSynapse myInput = null; InputConnector myInputConnector; Pattern myPattern; // myFirstRow, myCurrentRow and myLastRow will hold the relative // values of the input connector (which holds the absolute values ) // w.r.t. the input synpase holding the current row int myFirstRow = conn.getFirstRow(); int myCurrentRow = conn.getCurrentRow(); int myLastRow = conn.getLastRow(); int myNumberOfPatterns; // search for the synpase holding the current row of the connector for (int i=0; i < inputs.size(); ++i) { myInput = (StreamInputSynapse)inputs.elementAt(i); myNumberOfPatterns = getNumberOfPatterns(myInput); if(myFirstRow > myNumberOfPatterns) { // current input synpase does not contain the first (and therefore, // also not the current and last) row myFirstRow -= myNumberOfPatterns; myCurrentRow -= myNumberOfPatterns; if(myLastRow > 0) { myLastRow -= myNumberOfPatterns; } } else { // the current input synpase contains the first row if(myCurrentRow > myNumberOfPatterns) { // the current input synpase does not contain the current row myFirstRow = 1; myCurrentRow -= myNumberOfPatterns; if(myLastRow > 0) { myLastRow -= myNumberOfPatterns; } } else { // the current input synapse contains the current row if(myLastRow > myNumberOfPatterns) { // the current input synpase does not contain the last row myLastRow = 0; } // Synapse that contains the current row located. Create a new input // connector with the relative values for first, current and last row // w.r.t. the located input synpase. myInputConnector = new InputConnector(); myInputConnector.setFirstRow(myFirstRow); myInputConnector.setCurrentRow(myCurrentRow); myInputConnector.setLastRow(myLastRow); setActiveSynapse(myInput); myPattern = super.fwdGet(myInputConnector); if(myPattern.getCount() != -1) { myPattern.setCount(conn.getCurrentRow() - conn.getFirstRow()); } return myPattern; } } } return null; } /** * Gets (finds out) how many patters an input synpase holds. * * @param anInputSynpase the number of patterns for this input synpase will be * returned. * @return the number of patterns the <code>anInputSynpase</code> holds. */ protected int getNumberOfPatterns(StreamInputSynapse anInputSynpase) { if(anInputSynpase.getLastRow() != 0) { return anInputSynpase.getLastRow() - anInputSynpase.getFirstRow() + 1; } else if(anInputSynpase.getInputVector().size() != 0) { return anInputSynpase.getInputVector().size(); } else { // this method is only called if an input connector is connector to this // multiple input synpase. An input connector requires that its underlying // input synpase operates in buffer mode. Therefore, to be sure, we turn on // the buffermode if it is not on already... if(!anInputSynpase.isBuffered()) { anInputSynpase.setBuffered(true); } anInputSynpase.readAll(); return anInputSynpase.getInputVector().size(); } } private Pattern elaboratePattern(Pattern patt) { int count = patt.getCount(); if (count == -1) { currentInput = currentPatt = 0; } else { patt.setCount(++currentPatt); if (getActiveSynapse().isEOF()) { // The current Input Synapse reached the EOF, // then swicth to the next ++currentInput; if (currentInput == inputs.size()) { currentInput = currentPatt = 0; // Cycles if end of all the input synapses } } } return patt; } public void reset() { super.reset(); currentInput = currentPatt = 0; } /** * @param newBuffered boolean */ public void setBuffered(boolean newBuffered) { StreamInputSynapse myInput; for (int i=0; i < inputs.size(); ++i) { myInput = (StreamInputSynapse)inputs.elementAt(i); myInput.setBuffered(newBuffered); } } public void gotoLine(int aNumLine) throws IOException { StreamInputSynapse myInput = null; int myNumberOfPatterns; for (int i=0; i < inputs.size(); ++i) { myInput = (StreamInputSynapse)inputs.elementAt(i); myNumberOfPatterns = getNumberOfPatterns(myInput); if(aNumLine < myNumberOfPatterns + myInput.getFirstRow() - 1) { setActiveSynapse(myInput); myInput.gotoLine(aNumLine); return; // done } else { aNumLine -= myNumberOfPatterns; } } } public void setFirstRow(int newFirstRow) { // It doesn't make much sense to change the first row of this multiple input synpase // Control the first row either throught the underlying source or the 'above lying' // input connector throw new UnsupportedOperationException("Control the first row through the underlying source or any " + "connected input connectors"); } public void setLastRow(int newLastRow) { throw new UnsupportedOperationException("Control the last row through the underlying source or any " + "connected input connectors"); } }
Java
package org.joone.io; import java.beans.*; public class XLSInputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor//GEN-FIRST:BeanDescriptor private static BeanDescriptor beanDescriptor = new BeanDescriptor ( org.joone.io.XLSInputSynapse.class , null ); // NOI18N private static BeanDescriptor getBdescriptor(){ return beanDescriptor; } static {//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. }//GEN-LAST:BeanDescriptor // Property identifiers//GEN-FIRST:Properties private static final int PROPERTY_advancedColumnSelector = 0; private static final int PROPERTY_buffered = 1; private static final int PROPERTY_decimalPoint = 2; private static final int PROPERTY_enabled = 3; private static final int PROPERTY_firstRow = 4; private static final int PROPERTY_inputFile = 5; private static final int PROPERTY_inputPatterns = 6; private static final int PROPERTY_lastRow = 7; private static final int PROPERTY_monitor = 8; private static final int PROPERTY_name = 9; private static final int PROPERTY_plugIn = 10; private static final int PROPERTY_sheetName = 11; private static final int PROPERTY_stepCounter = 12; // Property array private static PropertyDescriptor[] properties = new PropertyDescriptor[13]; private static PropertyDescriptor[] getPdescriptor(){ return properties; } static { try { properties[PROPERTY_advancedColumnSelector] = new PropertyDescriptor ( "advancedColumnSelector", org.joone.io.XLSInputSynapse.class, "getAdvancedColumnSelector", "setAdvancedColumnSelector" ); // NOI18N properties[PROPERTY_advancedColumnSelector].setDisplayName ( "Advanced Column Selector" ); properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", org.joone.io.XLSInputSynapse.class, "isBuffered", "setBuffered" ); // NOI18N properties[PROPERTY_decimalPoint] = new PropertyDescriptor ( "decimalPoint", org.joone.io.XLSInputSynapse.class, "getDecimalPoint", "setDecimalPoint" ); // NOI18N properties[PROPERTY_decimalPoint].setExpert ( true ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", org.joone.io.XLSInputSynapse.class, "isEnabled", "setEnabled" ); // NOI18N properties[PROPERTY_firstRow] = new PropertyDescriptor ( "firstRow", org.joone.io.XLSInputSynapse.class, "getFirstRow", "setFirstRow" ); // NOI18N properties[PROPERTY_inputFile] = new PropertyDescriptor ( "inputFile", org.joone.io.XLSInputSynapse.class, "getInputFile", "setInputFile" ); // NOI18N properties[PROPERTY_inputPatterns] = new PropertyDescriptor ( "inputPatterns", org.joone.io.XLSInputSynapse.class, "getInputPatterns", "setInputPatterns" ); // NOI18N properties[PROPERTY_inputPatterns].setExpert ( true ); properties[PROPERTY_lastRow] = new PropertyDescriptor ( "lastRow", org.joone.io.XLSInputSynapse.class, "getLastRow", "setLastRow" ); // NOI18N properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", org.joone.io.XLSInputSynapse.class, "getMonitor", "setMonitor" ); // NOI18N properties[PROPERTY_monitor].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", org.joone.io.XLSInputSynapse.class, "getName", "setName" ); // NOI18N properties[PROPERTY_plugIn] = new PropertyDescriptor ( "plugIn", org.joone.io.XLSInputSynapse.class, "getPlugIn", "setPlugIn" ); // NOI18N properties[PROPERTY_plugIn].setExpert ( true ); properties[PROPERTY_sheetName] = new PropertyDescriptor ( "sheetName", org.joone.io.XLSInputSynapse.class, "getSheetName", "setSheetName" ); // NOI18N properties[PROPERTY_stepCounter] = new PropertyDescriptor ( "stepCounter", org.joone.io.XLSInputSynapse.class, "isStepCounter", "setStepCounter" ); // NOI18N } catch(IntrospectionException e) { e.printStackTrace(); }//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array private static EventSetDescriptor[] eventSets = new EventSetDescriptor[0]; private static EventSetDescriptor[] getEdescriptor(){ return eventSets; } //GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. //GEN-LAST:Events // Method identifiers//GEN-FIRST:Methods // Method array private static MethodDescriptor[] methods = new MethodDescriptor[0]; private static MethodDescriptor[] getMdescriptor(){ return methods; } //GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. //GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return beanDescriptor; } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return properties; } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return eventSets; } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return methods; } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.beans.*; public class ImageInputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( ImageInputSynapse.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_buffered = 0; private static final int PROPERTY_enabled = 1; private static final int PROPERTY_firstRow = 2; private static final int PROPERTY_lastRow = 3; private static final int PROPERTY_maxBufSize = 4; private static final int PROPERTY_name = 5; private static final int PROPERTY_plugIn = 6; private static final int PROPERTY_stepCounter = 7; private static final int PROPERTY_fileFilter = 8; private static final int PROPERTY_desiredWidth = 9; private static final int PROPERTY_desiredHeight = 10; private static final int PROPERTY_imageInput = 11; private static final int PROPERTY_imageDirectory = 12; private static final int PROPERTY_colourMode = 13; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[14]; try { properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", ImageInputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", ImageInputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_firstRow] = new PropertyDescriptor ( "firstRow", ImageInputSynapse.class, "getFirstRow", "setFirstRow" ); properties[PROPERTY_lastRow] = new PropertyDescriptor ( "lastRow", ImageInputSynapse.class, "getLastRow", "setLastRow" ); properties[PROPERTY_maxBufSize] = new PropertyDescriptor ( "maxBufSize", ImageInputSynapse.class, "getMaxBufSize", "setMaxBufSize" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", ImageInputSynapse.class, "getName", "setName" ); properties[PROPERTY_plugIn] = new PropertyDescriptor ( "plugIn", ImageInputSynapse.class, "getPlugIn", "setPlugIn" ); properties[PROPERTY_plugIn].setExpert ( true ); properties[PROPERTY_stepCounter] = new PropertyDescriptor ( "stepCounter", ImageInputSynapse.class, "isStepCounter", "setStepCounter" ); properties[PROPERTY_fileFilter] = new PropertyDescriptor ( "fileFilter", ImageInputSynapse.class, "getFileFilter", "setFileFilter" ); properties[PROPERTY_desiredWidth] = new PropertyDescriptor ( "scaleToWidth", ImageInputSynapse.class, "getDesiredWidth", "setDesiredWidth" ); properties[PROPERTY_desiredHeight] = new PropertyDescriptor ( "scaleToHeight", ImageInputSynapse.class, "getDesiredHeight", "setDesiredHeight" ); properties[PROPERTY_imageInput] = new PropertyDescriptor ( "imageInput", ImageInputSynapse.class, null, "setImageInput" ); properties[PROPERTY_imageInput].setExpert ( true ); properties[PROPERTY_imageDirectory] = new PropertyDescriptor ( "imageDirectory", ImageInputSynapse.class, "getImageDirectory", "setImageDirectory" ); properties[PROPERTY_colourMode] = new PropertyDescriptor ( "colourMode", ImageInputSynapse.class, "getColourMode", "setColourMode" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods private static final int METHOD_addNoise0 = 0; private static final int METHOD_canCountSteps1 = 1; private static final int METHOD_check2 = 2; private static final int METHOD_fwdGet3 = 3; private static final int METHOD_fwdPut4 = 4; private static final int METHOD_gotoFirstLine5 = 5; private static final int METHOD_gotoLine6 = 6; private static final int METHOD_initLearner7 = 7; private static final int METHOD_numColumns8 = 8; private static final int METHOD_randomize9 = 9; private static final int METHOD_readAll10 = 10; private static final int METHOD_reset11 = 11; private static final int METHOD_resetInput12 = 12; private static final int METHOD_revGet13 = 13; private static final int METHOD_revPut14 = 14; // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[15]; try { methods[METHOD_addNoise0] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("addNoise", new Class[] {Double.TYPE})); methods[METHOD_addNoise0].setDisplayName ( "" ); methods[METHOD_canCountSteps1] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("canCountSteps", new Class[] {})); methods[METHOD_canCountSteps1].setDisplayName ( "" ); methods[METHOD_check2] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("check", new Class[] {})); methods[METHOD_check2].setDisplayName ( "" ); methods[METHOD_fwdGet3] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("fwdGet", new Class[] {})); methods[METHOD_fwdGet3].setDisplayName ( "" ); methods[METHOD_fwdPut4] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("fwdPut", new Class[] {org.joone.engine.Pattern.class})); methods[METHOD_fwdPut4].setDisplayName ( "" ); methods[METHOD_gotoFirstLine5] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("gotoFirstLine", new Class[] {})); methods[METHOD_gotoFirstLine5].setDisplayName ( "" ); methods[METHOD_gotoLine6] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("gotoLine", new Class[] {Integer.TYPE})); methods[METHOD_gotoLine6].setDisplayName ( "" ); methods[METHOD_initLearner7] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("initLearner", new Class[] {})); methods[METHOD_initLearner7].setDisplayName ( "" ); methods[METHOD_numColumns8] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("numColumns", new Class[] {})); methods[METHOD_numColumns8].setDisplayName ( "" ); methods[METHOD_randomize9] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("randomize", new Class[] {Double.TYPE})); methods[METHOD_randomize9].setDisplayName ( "" ); methods[METHOD_readAll10] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("readAll", new Class[] {})); methods[METHOD_readAll10].setDisplayName ( "" ); methods[METHOD_reset11] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("reset", new Class[] {})); methods[METHOD_reset11].setDisplayName ( "" ); methods[METHOD_resetInput12] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("resetInput", new Class[] {})); methods[METHOD_resetInput12].setDisplayName ( "" ); methods[METHOD_revGet13] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("revGet", new Class[] {})); methods[METHOD_revGet13].setDisplayName ( "" ); methods[METHOD_revPut14] = new MethodDescriptor ( org.joone.io.ImageInputSynapse.class.getMethod("revPut", new Class[] {org.joone.engine.Pattern.class})); methods[METHOD_revPut14].setDisplayName ( "" ); } catch( Exception e) {}//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.beans.*; public class StreamOutputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( StreamOutputSynapse.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_buffered = 0; private static final int PROPERTY_enabled = 1; private static final int PROPERTY_separator = 2; private static final int PROPERTY_name = 3; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[4]; try { properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", StreamOutputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", StreamOutputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_separator] = new PropertyDescriptor ( "separator", StreamOutputSynapse.class, "getSeparator", "setSeparator" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", StreamOutputSynapse.class, "getName", "setName" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
/* * MemoryOutputSynapse.java * * Created on 6 maggio 2002, 21.45 */ package org.joone.io; import org.joone.engine.*; import java.util.Vector; import org.joone.log.*; /** * * @author pmarrone */ public class MemoryOutputSynapse extends StreamOutputSynapse { static final long serialVersionUID = 1342649629529016627L; /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(Synapse.class); private Fifo patterns; private boolean zeroPattern = false; /** Creates a new instance of MemoryOutputSynapse */ public MemoryOutputSynapse() { } /** * Returns all the patterns received in the last cycle * @return a vector containing the output patterns */ private synchronized Vector getPatterns() { if (patterns == null) patterns = new Fifo(); return (Vector)patterns.clone(); } /** * This method waits for the zeroPattern and returns the last valid pattern received * * @return the last pattern received */ public synchronized double[] getLastPattern() { Pattern pOut; // Wait until the 'stop pattern' is received while (!zeroPattern) { try { wait(); } catch (InterruptedException e) { } } int size = patterns.size(); zeroPattern = false; if (size > 0) { pOut = (Pattern)patterns.elementAt(size - 1); return pOut.getArray(); } else return null; } /** * Waits for the next pattern and returns it * * @return the next pattern */ public synchronized double[] getNextPattern() { while (getPatterns().isEmpty()) { try { wait(); } catch (InterruptedException e) { } } Pattern pOut = (Pattern)patterns.pop(); return pOut.getArray(); } /** * Waits for the stopPattern and then returns all the patterns received in * the last cycle * * @return all the patterns received in the last cycle */ public synchronized Vector getAllPatterns() { getLastPattern(); return getPatterns(); } /** Custom Synapses need to implement at least this method. The custom synapse should write the pattern out to the * appropriate media. All patterns including the ending pattern with pattern.getCount()=-1 will be passed to this method so that * custom output synapses can perform final processing. * */ public synchronized void write(Pattern pattern) { count = pattern.getCount(); if (count == 1) { patterns = new Fifo(); } if ( count > -1) // If we still going through patterns then simply add them to the memory buffer { patterns.push(pattern); zeroPattern = false; } else zeroPattern = true; notifyAll(); } }
Java
package org.joone.io; import java.beans.*; public class FileInputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor//GEN-FIRST:BeanDescriptor private static BeanDescriptor beanDescriptor = new BeanDescriptor ( org.joone.io.FileInputSynapse.class , null ); // NOI18N private static BeanDescriptor getBdescriptor(){ return beanDescriptor; } static {//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. }//GEN-LAST:BeanDescriptor // Property identifiers//GEN-FIRST:Properties private static final int PROPERTY_advancedColumnSelector = 0; private static final int PROPERTY_buffered = 1; private static final int PROPERTY_decimalPoint = 2; private static final int PROPERTY_enabled = 3; private static final int PROPERTY_firstRow = 4; private static final int PROPERTY_inputFile = 5; private static final int PROPERTY_inputPatterns = 6; private static final int PROPERTY_lastRow = 7; private static final int PROPERTY_maxBufSize = 8; private static final int PROPERTY_monitor = 9; private static final int PROPERTY_name = 10; private static final int PROPERTY_plugIn = 11; private static final int PROPERTY_stepCounter = 12; // Property array private static PropertyDescriptor[] properties = new PropertyDescriptor[13]; private static PropertyDescriptor[] getPdescriptor(){ return properties; } static { try { properties[PROPERTY_advancedColumnSelector] = new PropertyDescriptor ( "advancedColumnSelector", org.joone.io.FileInputSynapse.class, "getAdvancedColumnSelector", "setAdvancedColumnSelector" ); // NOI18N properties[PROPERTY_advancedColumnSelector].setDisplayName ( "Advanced Column Selector" ); properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", org.joone.io.FileInputSynapse.class, "isBuffered", "setBuffered" ); // NOI18N properties[PROPERTY_decimalPoint] = new PropertyDescriptor ( "decimalPoint", org.joone.io.FileInputSynapse.class, "getDecimalPoint", "setDecimalPoint" ); // NOI18N properties[PROPERTY_decimalPoint].setExpert ( true ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", org.joone.io.FileInputSynapse.class, "isEnabled", "setEnabled" ); // NOI18N properties[PROPERTY_firstRow] = new PropertyDescriptor ( "firstRow", org.joone.io.FileInputSynapse.class, "getFirstRow", "setFirstRow" ); // NOI18N properties[PROPERTY_inputFile] = new PropertyDescriptor ( "inputFile", org.joone.io.FileInputSynapse.class, "getInputFile", "setInputFile" ); // NOI18N properties[PROPERTY_inputPatterns] = new PropertyDescriptor ( "inputPatterns", org.joone.io.FileInputSynapse.class, "getInputPatterns", "setInputPatterns" ); // NOI18N properties[PROPERTY_inputPatterns].setExpert ( true ); properties[PROPERTY_lastRow] = new PropertyDescriptor ( "lastRow", org.joone.io.FileInputSynapse.class, "getLastRow", "setLastRow" ); // NOI18N properties[PROPERTY_maxBufSize] = new PropertyDescriptor ( "maxBufSize", org.joone.io.FileInputSynapse.class, "getMaxBufSize", "setMaxBufSize" ); // NOI18N properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", org.joone.io.FileInputSynapse.class, "getMonitor", "setMonitor" ); // NOI18N properties[PROPERTY_monitor].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", org.joone.io.FileInputSynapse.class, "getName", "setName" ); // NOI18N properties[PROPERTY_plugIn] = new PropertyDescriptor ( "plugIn", org.joone.io.FileInputSynapse.class, "getPlugIn", "setPlugIn" ); // NOI18N properties[PROPERTY_plugIn].setExpert ( true ); properties[PROPERTY_stepCounter] = new PropertyDescriptor ( "stepCounter", org.joone.io.FileInputSynapse.class, "isStepCounter", "setStepCounter" ); // NOI18N } catch(IntrospectionException e) { e.printStackTrace(); }//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array private static EventSetDescriptor[] eventSets = new EventSetDescriptor[0]; private static EventSetDescriptor[] getEdescriptor(){ return eventSets; } //GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. //GEN-LAST:Events // Method identifiers//GEN-FIRST:Methods private static final int METHOD_addNoise0 = 0; private static final int METHOD_canCountSteps1 = 1; private static final int METHOD_fwdGet2 = 2; private static final int METHOD_fwdPut3 = 3; private static final int METHOD_gotoFirstLine4 = 4; private static final int METHOD_gotoLine5 = 5; private static final int METHOD_readAll6 = 6; private static final int METHOD_revGet7 = 7; private static final int METHOD_revPut8 = 8; // Method array private static MethodDescriptor[] methods = new MethodDescriptor[9]; private static MethodDescriptor[] getMdescriptor(){ return methods; } static { try { methods[METHOD_addNoise0] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("addNoise", new Class[] {Double.TYPE})); // NOI18N methods[METHOD_addNoise0].setDisplayName ( "" ); methods[METHOD_canCountSteps1] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("canCountSteps", new Class[] {})); // NOI18N methods[METHOD_canCountSteps1].setDisplayName ( "" ); methods[METHOD_fwdGet2] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("fwdGet", new Class[] {})); // NOI18N methods[METHOD_fwdGet2].setDisplayName ( "" ); methods[METHOD_fwdPut3] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("fwdPut", new Class[] {org.joone.engine.Pattern.class})); // NOI18N methods[METHOD_fwdPut3].setDisplayName ( "" ); methods[METHOD_gotoFirstLine4] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("gotoFirstLine", new Class[] {})); // NOI18N methods[METHOD_gotoFirstLine4].setDisplayName ( "" ); methods[METHOD_gotoLine5] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("gotoLine", new Class[] {Integer.TYPE})); // NOI18N methods[METHOD_gotoLine5].setDisplayName ( "" ); methods[METHOD_readAll6] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("readAll", new Class[] {})); // NOI18N methods[METHOD_readAll6].setDisplayName ( "" ); methods[METHOD_revGet7] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("revGet", new Class[] {})); // NOI18N methods[METHOD_revGet7].setDisplayName ( "" ); methods[METHOD_revPut8] = new MethodDescriptor ( org.joone.io.FileInputSynapse.class.getMethod("revPut", new Class[] {org.joone.engine.Pattern.class})); // NOI18N methods[METHOD_revPut8].setDisplayName ( "" ); } catch( Exception e) {}//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return beanDescriptor; } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return properties; } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return eventSets; } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return methods; } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import org.joone.util.*; public interface InputSynapse extends PlugInListener { public char getDecimalPoint(); public int getFirstRow(); public int getLastRow(); public void gotoFirstLine() throws java.io.IOException; public void gotoLine(int numLine) throws java.io.IOException; public boolean isBuffered(); public boolean isEOF(); // Read all input values and fullfills the buffer public void readAll(); public void setBuffered(boolean newBuffered); public void setDecimalPoint(char dp); public void setFirstRow(int newFirstRow); public void setLastRow(int newLastRow); public void setFirstCol(int numcol) throws IllegalArgumentException; public void setLastCol(int numcol) throws IllegalArgumentException; public int getFirstCol(); public int getLastCol(); public void resetInput(); /** Returns true if this input layer is an active counter of the steps. * Warning: in a neural net there can be only one StepCounter element! * (10/04/00 23.23.26) * @return boolean * */ public boolean isStepCounter(); /** Set to true if this input layer is an active counter of the steps. * Warning: in a neural net there can be only one StepCounter element! * (10/04/00 23.23.26) * @param newStepCounter boolean * */ public void setStepCounter(boolean newStepCounter); }
Java
package org.joone.io; import java.beans.*; public class YahooFinanceInputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor//GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( org.joone.io.YahooFinanceInputSynapse.class , null ); // NOI18N//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers//GEN-FIRST:Properties private static final int PROPERTY_advancedColumnSelector = 0; private static final int PROPERTY_buffered = 1; private static final int PROPERTY_enabled = 2; private static final int PROPERTY_endDate = 3; private static final int PROPERTY_firstRow = 4; private static final int PROPERTY_lastRow = 5; private static final int PROPERTY_maxBufSize = 6; private static final int PROPERTY_name = 7; private static final int PROPERTY_period = 8; private static final int PROPERTY_plugIn = 9; private static final int PROPERTY_startDate = 10; private static final int PROPERTY_stepCounter = 11; private static final int PROPERTY_stockData = 12; private static final int PROPERTY_symbol = 13; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[14]; try { properties[PROPERTY_advancedColumnSelector] = new PropertyDescriptor ( "advancedColumnSelector", org.joone.io.YahooFinanceInputSynapse.class, "getAdvancedColumnSelector", "setAdvancedColumnSelector" ); // NOI18N properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", org.joone.io.YahooFinanceInputSynapse.class, "isBuffered", "setBuffered" ); // NOI18N properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", org.joone.io.YahooFinanceInputSynapse.class, "isEnabled", "setEnabled" ); // NOI18N properties[PROPERTY_endDate] = new PropertyDescriptor ( "endDate", org.joone.io.YahooFinanceInputSynapse.class, "getEndDate", "setEndDate" ); // NOI18N properties[PROPERTY_firstRow] = new PropertyDescriptor ( "firstRow", org.joone.io.YahooFinanceInputSynapse.class, "getFirstRow", "setFirstRow" ); // NOI18N properties[PROPERTY_lastRow] = new PropertyDescriptor ( "lastRow", org.joone.io.YahooFinanceInputSynapse.class, "getLastRow", "setLastRow" ); // NOI18N properties[PROPERTY_maxBufSize] = new PropertyDescriptor ( "maxBufSize", org.joone.io.YahooFinanceInputSynapse.class, "getMaxBufSize", "setMaxBufSize" ); // NOI18N properties[PROPERTY_name] = new PropertyDescriptor ( "name", org.joone.io.YahooFinanceInputSynapse.class, "getName", "setName" ); // NOI18N properties[PROPERTY_period] = new PropertyDescriptor ( "period", org.joone.io.YahooFinanceInputSynapse.class, "getPeriod", "setPeriod" ); // NOI18N properties[PROPERTY_plugIn] = new PropertyDescriptor ( "plugIn", org.joone.io.YahooFinanceInputSynapse.class, "getPlugIn", "setPlugIn" ); // NOI18N properties[PROPERTY_plugIn].setExpert ( true ); properties[PROPERTY_startDate] = new PropertyDescriptor ( "startDate", org.joone.io.YahooFinanceInputSynapse.class, "getStartDate", "setStartDate" ); // NOI18N properties[PROPERTY_stepCounter] = new PropertyDescriptor ( "stepCounter", org.joone.io.YahooFinanceInputSynapse.class, "isStepCounter", "setStepCounter" ); // NOI18N properties[PROPERTY_stockData] = new PropertyDescriptor ( "stockData", org.joone.io.YahooFinanceInputSynapse.class, "getStockData", null ); // NOI18N properties[PROPERTY_symbol] = new PropertyDescriptor ( "symbol", org.joone.io.YahooFinanceInputSynapse.class, "getSymbol", "setSymbol" ); // NOI18N } catch(IntrospectionException e) { e.printStackTrace(); }//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers//GEN-FIRST:Methods private static final int METHOD_addNoise0 = 0; private static final int METHOD_canCountSteps1 = 1; private static final int METHOD_check2 = 2; private static final int METHOD_fwdGet3 = 3; private static final int METHOD_fwdPut4 = 4; private static final int METHOD_gotoFirstLine5 = 5; private static final int METHOD_gotoLine6 = 6; private static final int METHOD_initLearner7 = 7; private static final int METHOD_numColumns8 = 8; private static final int METHOD_randomize9 = 9; private static final int METHOD_readAll10 = 10; private static final int METHOD_reset11 = 11; private static final int METHOD_resetInput12 = 12; private static final int METHOD_revGet13 = 13; private static final int METHOD_revPut14 = 14; // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[15]; try { methods[METHOD_addNoise0] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("addNoise", new Class[] {Double.TYPE})); // NOI18N methods[METHOD_addNoise0].setDisplayName ( "" ); methods[METHOD_canCountSteps1] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("canCountSteps", new Class[] {})); // NOI18N methods[METHOD_canCountSteps1].setDisplayName ( "" ); methods[METHOD_check2] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("check", new Class[] {})); // NOI18N methods[METHOD_check2].setDisplayName ( "" ); methods[METHOD_fwdGet3] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("fwdGet", new Class[] {})); // NOI18N methods[METHOD_fwdGet3].setDisplayName ( "" ); methods[METHOD_fwdPut4] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("fwdPut", new Class[] {org.joone.engine.Pattern.class})); // NOI18N methods[METHOD_fwdPut4].setDisplayName ( "" ); methods[METHOD_gotoFirstLine5] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("gotoFirstLine", new Class[] {})); // NOI18N methods[METHOD_gotoFirstLine5].setDisplayName ( "" ); methods[METHOD_gotoLine6] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("gotoLine", new Class[] {Integer.TYPE})); // NOI18N methods[METHOD_gotoLine6].setDisplayName ( "" ); methods[METHOD_initLearner7] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("initLearner", new Class[] {})); // NOI18N methods[METHOD_initLearner7].setDisplayName ( "" ); methods[METHOD_numColumns8] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("numColumns", new Class[] {})); // NOI18N methods[METHOD_numColumns8].setDisplayName ( "" ); methods[METHOD_randomize9] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("randomize", new Class[] {Double.TYPE})); // NOI18N methods[METHOD_randomize9].setDisplayName ( "" ); methods[METHOD_readAll10] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("readAll", new Class[] {})); // NOI18N methods[METHOD_readAll10].setDisplayName ( "" ); methods[METHOD_reset11] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("reset", new Class[] {})); // NOI18N methods[METHOD_reset11].setDisplayName ( "" ); methods[METHOD_resetInput12] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("resetInput", new Class[] {})); // NOI18N methods[METHOD_resetInput12].setDisplayName ( "" ); methods[METHOD_revGet13] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("revGet", new Class[] {})); // NOI18N methods[METHOD_revGet13].setDisplayName ( "" ); methods[METHOD_revPut14] = new MethodDescriptor ( org.joone.io.YahooFinanceInputSynapse.class.getMethod("revPut", new Class[] {org.joone.engine.Pattern.class})); // NOI18N methods[METHOD_revPut14].setDisplayName ( "" ); } catch( Exception e) {}//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.io.*; import java.sql.*; import java.util.*; import org.joone.net.NetCheck; import org.joone.exception.JooneRuntimeException; import org.joone.engine.NetErrorManager; import org.joone.log.*; /** * <P>The JDBCInputSynapse provides support for data extraction from a database. * To use this synapse the user should ensure a JDBC Type 4 Driver is in the class path. * It is possible to use other JDBC driver types though you will have to refer to the vendors documentation, * it may require extra software insallation and this may limit your distributtion to certain Operating Systems.</P> * <P>The properties required by this JDBCInputSynapse Plugin are the following</P> * <P>Database Driver Name - e.g sun.jdbc.odbc.JdbcOdbcDriver</P> * <P>Database URL - e.g jdbc:mysql://localhost/MyDb?user=myuser&password=mypass * <P>SQLquery - e.g select val1,val2,result from xor;</P> * <P>Advanced Column Selector - This selects the values from the query result e.g '1,2' would * select val1 and val2. in this case. * <P>Note : The database URL uses specific protocol after the "jdbc:" section check with the jdbc driver vendor for specific info.</P> * <P>Some commonly used Driver protocols shown below ...</P> * <BR> * <P>Driver {com.mysql.jdbc.Driver} </P> * <P>Protocol {jdbc:mysql://[hostname][,failoverhost...][:port]/[dbname][?param1=value1][&param2=value2].....} MySQL Protool </P> * <P>Example {jdbc:mysql://localhost/test?user=blah&password=blah} </P> * <P>Web Site {http://www.mysql.com} </P> * <BR> * <P>Driver {sun.jdbc.odbc.JdbcOdbcDriver} </P> * <P>Protocol { jdbc:odbc:<data-source-name>[;<attribute-name>=<attribute-value>]* } ODBC Protocol </P> * <P>Example {jdbc:odbc:mydb;UID=me;PWD=secret} </P> * <P>Web Site {http://www.java.sun.com} </P> * <BR> * <P>Data Types</P> * <BR> * <P>Any fields selected from a database should contain a single double or float format value. The * data type is not so important it can be text or a number field so long as it contains just * one double or float format value.</P> * <P>E.g Correct = '2.31' Wrong= '3.45;1.21' and Wrong = 'hello' </P> * * @author Julien Norman * @created 29/11/2002 */ public class JDBCInputSynapse extends StreamInputSynapse { /** The object used when logging debug,errors,warnings and info. */ private static final ILogger log = LoggerFactory.getLogger(JDBCInputSynapse.class); /** The name of the JDBC Database driver. */ private String driverName = ""; /** The URL of the database. */ private String dbURL = ""; /** The database query to use in order to obtain the input data. */ private String SQLQuery = ""; private final static long serialVersionUID = -4642657913289986240L; /** *Constructor for the JDBCInputSynapse object */ public JDBCInputSynapse() { super(); } /** * <P>Constructor for the JDBCInputSynapse object that allows all options. * Allows the user to construct a JDBCInputSynapse in one call.</P> * @param newDrivername The class name of the database driver to use. * @param newdbURL The Universal Resource Locator to enable connection to the database. * @param newSQLQuery The database SQL query to apply to the database. * @param newAdvColSel The comma delimited selection of what data columns to use. * @param newfirstRow The first row to apply to the network. * @param newlastRow The last row to apply to the network. * @param buffered Whether this synapse is buffered or not. */ public JDBCInputSynapse(String newDrivername,String newdbURL, String newSQLQuery,String newAdvColSel,int newfirstRow,int newlastRow,boolean buffered) { super(); setBuffered(buffered); setFirstRow(newfirstRow); setLastRow(newlastRow); setAdvancedColumnSelector(newAdvColSel); setdriverName(newDrivername); setdbURL(newdbURL); setSQLQuery(newSQLQuery); } /** * Gets the name of the database jdbc driver used by this JDBC input syanpse. * * @return The JDBC Driver name */ public java.lang.String getdriverName() { return driverName; } /** * Gets the name of the database Universal Resource Location (URL) * * @return The database URL used by this JDBC input syanpse. */ public java.lang.String getdbURL() { return dbURL; } /** * Gets the SQL Query used to select data from the database. * * @return The sQLQuery used by this JDBC input syanpse. */ public java.lang.String getSQLQuery() { return SQLQuery; } /** * Reads this JDBCInputSynapse object into memory * * @param in The object input stream that this object should be read from * @exception IOException The Input Output Exception * @exception ClassNotFoundException The class not found exception */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { super.readObjectBase(in); if (in.getClass().getName().indexOf("xstream") == -1) { driverName = (String) in.readObject(); dbURL = (String) in.readObject(); SQLQuery = (String) in.readObject(); } if (!isBuffered() || (getInputVector().size() == 0)) { setdriverName(driverName); } } /** * Sets the name of the database jdbc driver. * * @param newDriverName The JDBC Driver name */ public void setdriverName(java.lang.String newDriverName) { // Check that it's actually changed. if (!newDriverName.equals(driverName)) { driverName = newDriverName; this.resetInput(); this.setTokens(null); } // Check all params have been set then call the initInputStream to read the data in. /* if ( (driverName != null) && (!driverName.equals("")) ) if ( (dbURL != null) && (!dbURL.equals("")) ) if ( (SQLQuery != null) && (!SQLQuery.equals(""))) initInputStream(); */ } /** * Gets the name of the database Universal Resource Location (URL) * * @param newdbURL The database URL to use for selecting input. See the notes on this class for usage. */ public void setdbURL(java.lang.String newdbURL) { // Check it's actually changed. if (!dbURL.equals(newdbURL) ) { dbURL = newdbURL; this.resetInput(); this.setTokens(null); } // Check all params have been set then call the initInputStream to read the data in. /*if ( (driverName != null) && (!driverName.equals("")) ) if ( (dbURL != null) && (!dbURL.equals("")) ) if ( (SQLQuery != null) && (!SQLQuery.equals(""))) initInputStream(); */ } /** * Sets the sQLQuery attribute of the JDBCInputSynapse object * * @param newSQLQuery The new database SQL Query. */ public void setSQLQuery(java.lang.String newSQLQuery) { // Check that it's actually changed. if (!SQLQuery.equals(newSQLQuery) ) { SQLQuery = newSQLQuery; this.resetInput(); this.setTokens(null); } // Check all params have been set then call the initInputStream to read the data in. /*if ( (driverName != null) && (!driverName.equals("")) ) if ( (dbURL != null) && (!dbURL.equals("")) ) if ( (SQLQuery != null) && (!SQLQuery.equals(""))) initInputStream(); */ } /** * Writes this JDBCSynapseInput object to the ObjectOutputStream out. * * @param out The ObjectOutputSteeam that this object should be written to * @exception IOException The Input Output Exception if any */ private void writeObject(ObjectOutputStream out) throws IOException { super.writeObjectBase(out); if (out.getClass().getName().indexOf("xstream") == -1) { out.writeObject(driverName); out.writeObject(dbURL); out.writeObject(SQLQuery); } } /** * Connects to the database using Driver name and db URL and selects data using the SQLQuery. */ protected void initInputStream() throws JooneRuntimeException { Connection con; // This will contain pattern set // Ensure all properties have been set if ((driverName != null) && (!driverName.equals(new String("")))) { // Check that Driver Name has been set if ((dbURL != null) && (!dbURL.equals(new String("")))) { // Check that Database URL has been set if ((SQLQuery != null) && (!SQLQuery.equals(new String("")))) { // Check that SQLQuery has been set try { Class.forName(driverName); // E.g sun.jdbc.odbc.JdbcOdbcDriver to use JDBC:ODBC bridge con = DriverManager.getConnection(dbURL); // URL if you have Fred ODBC Data source then e.g jdbc:odbc:Fred Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(SQLQuery); StringBuffer SQLNetInput = new StringBuffer(); while (rs.next()) { if (rs.getMetaData().getColumnCount() >= 1) { SQLNetInput.append(rs.getDouble(1)); // Get first Column } for (int counter = 2; counter <= rs.getMetaData().getColumnCount(); counter++) { // Loop through remaining columns SQLNetInput.append(";"); SQLNetInput.append(rs.getDouble(counter)); // Add data from ResultSet } SQLNetInput.append('\n'); // Add a new line after completion of a pattern } StreamInputTokenizer sit; if (getMaxBufSize() > 0) sit = new StreamInputTokenizer(new StringReader(SQLNetInput.toString()), getMaxBufSize()); else sit = new StreamInputTokenizer(new StringReader(SQLNetInput.toString())); super.setTokens(sit); } catch (ClassNotFoundException ex) { // Use Log4j log.error( "Could not find Database Driver Class while initializing the JDBCInputStream. Message is : " + ex.getMessage(), ex ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Could not find Database Driver Class while initializing the JDBCInputStream. Message is : " + ex.getMessage()); //System.out.println("Could not find Database Driver Class while initializing the JDBCInputStream. Message is : " + ex.getMessage()); // SYS LOG } catch (SQLException sqlex) { // Use Log4j log.error( "SQLException thrown while initializing the JDBCInputStream. Message is : " + sqlex.getMessage(), sqlex ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"SQLException thrown while initializing the JDBCInputStream. Message is : " + sqlex.getMessage()); //System.out.println("SQLException thrown while initializing the JDBCInputStream. Message is : " + sqlex.getMessage()); // SYS LOG } catch (IOException ex) { // Use Log4j log.error( "IOException thrown while initializing the JDBCInputStream. Message is : " + ex.getMessage(), ex ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"IOException thrown while initializing the JDBCInputStream. Message is : " + ex.getMessage()); //System.out.println("IOException thrown while initializing the JDBCInputStream. Message is : " + ex.getMessage()); // SYS LOG } } else { // Warn the user or app that the SQLQuery has not been set String err = "The SQL Query has not been entered!"; log.warn( err ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"The SQL Query has not been entered!"); } } else { // Warn the user or app that the Database URL has not been set String err = "The Database URL has not been entered!"; log.warn( err ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"The Database URL has not been entered!"); } } else { // Warn user or app that the Driver Name has not been set String err = "The Driver Name has not been entered!"; log.warn( err ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"The Driver Name has not been entered!"); } } /** * Check that parameters are set correctly for the this JDBCInputSynapse object. * * @see Synapse * @return validation errors. */ public TreeSet check() { // Get the parent's check messages. TreeSet checks = super.check(); Connection con; // To test the connection. // See if the driver name has been entered. if ((driverName == null)||(driverName.compareTo("")==0)) { checks.add(new NetCheck(NetCheck.FATAL, "Database Driver Name needs to be entered.", this)); } else { // Driver Name entered check that it is valid try { Class.forName(driverName); // Check driver class is correct E.g sun.jdbc.odbc.JdbcOdbcDriver to use JDBC:ODBC bridge // See if we can get a connection if there is a URL entered.... if ((dbURL != null)&&(dbURL.compareTo("")!=0)) { con = DriverManager.getConnection(dbURL); } } catch (ClassNotFoundException ex) { // Use Log4j checks.add(new NetCheck(NetCheck.FATAL, "Could not find Database Driver Class. Check Database Driver is in the classpath and is readable.",this)); // LOG4J } catch (SQLException sqlex) { checks.add(new NetCheck(NetCheck.FATAL, "The Database URL is incorrect. Connection error is : "+sqlex.toString(),this)); // LOG4J } } // Check that the dbURL has been entered. if ((dbURL == null)||(dbURL.compareTo("")==0)) { checks.add(new NetCheck(NetCheck.FATAL, "Database URL needs to be entered.", this)); } // Check that the SQLQuery has been entered if ((SQLQuery == null)||(SQLQuery.compareTo("")==0)) { checks.add(new NetCheck(NetCheck.FATAL, "Database SQL Query needs to be entered.", this)); } return checks; } }
Java
/* * ImageInputSynapse.java * * Created on 16 October 2005, 08:50 * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package org.joone.io; import java.util.Vector; import java.awt.Image; import java.io.File; import java.io.FilenameFilter; import java.net.URL; import java.util.TreeSet; import org.joone.log.*; import org.joone.net.NetCheck; /** * This synapse collects data from Image files or Image objects and feeds the data from the Images into the Neural network. * GIF, JPG and PNG image file formats can be read. The synapse operates in two modes, colour and grey scale. * <P> * <B>Colour Mode</B> * In colour mode ImageInputSynapse produces seperate RGB input values in the range 0 to 1 from the * image. So using an image of width 10 and height 10 there will be 10x10x3 inputs in the range 0 to 1. * The individual colour components are calculated by obtaining the RGB values from the image. These value * are initially in an ARGB format. Transparency is removed and the RGB value extracted and normalised * between 0 and 1. * </P> * <P> * <B>Non Colour Mode / Grey Scale Mode </B> * In this mode the synapse treats each input value as a grey scale value for each pixel. In this mode * only Width*Height values are required. To produce the final image the Red, Green and Blue components * are the set to this same value. * The grey scale component is calculated by obtaining the RGB values from the image. These value * are initially in an ARGB format. Transparency is removed and the RGB value extracted, averaged and normalised * to produce one grey scale value between 0 and 1. * </P> * @author Julien Norman */ public class ImageInputSynapse extends StreamInputSynapse { /** The object used when logging debug,errors,warnings and info. */ private static final ILogger log = LoggerFactory.getLogger(ImageInputSynapse.class); static final long serialVersionUID = -1396287146739057882L; private File imageDirectory = new File(System.getProperty("user.dir")); private String theFileFilter = new String(".*[jJ][pP][gG]"); private Vector FileNameList = new Vector(); private Image [] MultiImages = null; private int DesiredWidth = 10; private int DesiredHeight = 10; /** * If in Colour Mode RGB values are input seperately. * Otherwise RGB values are averaged and input as grey scale. */ private boolean ColourMode = true; /** Creates a new instance of ImageInputSynapse */ public ImageInputSynapse() { this.calculateNewACS(); } /* Specific ImageInputSynapse Methods */ public void setFileFilter(String newFileFilter) { theFileFilter = newFileFilter; } public String getFileFilter() { return(theFileFilter); } public void setImageInput(Image [] theImages) { MultiImages = theImages; } protected void initInputStream() throws org.joone.exception.JooneRuntimeException { ImageInputTokenizer toks = null; try { if ( (MultiImages != null) && (MultiImages.length > 0)) { toks = new ImageInputTokenizer(getDesiredWidth(), getDesiredHeight(), MultiImages,ColourMode ); super.setTokens(toks); } else { FileNameList = new Vector(); String [] thelist = imageDirectory.list( new FilenameFilter() { public boolean accept(File dir, String name) { return name.matches(theFileFilter); } }); for (int i=0;i<thelist.length;i++) { URL theurl = new File(imageDirectory.getPath() + System.getProperty("file.separator") + thelist[i]).toURL(); FileNameList.add(theurl); } toks = new ImageInputTokenizer(getDesiredWidth(), getDesiredHeight(), FileNameList,ColourMode ); super.setTokens(toks); } } catch(Exception ex) { // Report the error. log.error("Error initialising the input stream : "+ex.toString()); } } public int getDesiredWidth() { return DesiredWidth; } public void setDesiredWidth(int DesiredWidth) { this.DesiredWidth = DesiredWidth; this.calculateNewACS(); } public int getDesiredHeight() { return DesiredHeight; } public void setDesiredHeight(int DesiredHeight) { this.DesiredHeight = DesiredHeight; this.calculateNewACS(); } public File getImageDirectory() { return imageDirectory; } public void setImageDirectory(File imgDir) { File tmpDir = imgDir; if ((tmpDir != null) && (!tmpDir.isDirectory())) { String name = tmpDir.getName(); int pos = tmpDir.getPath().indexOf(name); if (pos > -1) { String dir = tmpDir.getPath().substring(0, pos); tmpDir = new File(dir); } } this.imageDirectory = tmpDir; } public boolean getColourMode() { return ColourMode; } public void setColourMode(boolean ColourMode) { this.ColourMode = ColourMode; this.calculateNewACS(); } /** Checks and returns any problems found with the settings of this synapse. * @return A TreeSet of problems or errors found with this synapse. */ public TreeSet check() { TreeSet checks = super.check(); if (theFileFilter.equals("")) { checks.add(new NetCheck(NetCheck.FATAL, "No File Filter set e.g. '.*[jJ][pP][gG]'." , this)); } if ( imageDirectory == null ) { checks.add(new NetCheck(NetCheck.FATAL, "No image input directory set." , this)); } return checks; } /** Calculates the new value for AdvancedColumnSelector */ protected void calculateNewACS() { int tokens = this.DesiredWidth*this.DesiredHeight; if ( ColourMode ) tokens = tokens * 3; this.setAdvancedColumnSelector("1-"+tokens); } }
Java
package org.joone.io; import java.beans.*; public class XLSOutputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( XLSOutputSynapse.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_sheetName = 0; private static final int PROPERTY_buffered = 1; private static final int PROPERTY_fileName = 2; private static final int PROPERTY_enabled = 3; private static final int PROPERTY_separator = 4; private static final int PROPERTY_name = 5; private static final int PROPERTY_monitor = 6; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[7]; try { properties[PROPERTY_sheetName] = new PropertyDescriptor ( "sheetName", XLSOutputSynapse.class, "getSheetName", "setSheetName" ); properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", XLSOutputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_fileName] = new PropertyDescriptor ( "fileName", XLSOutputSynapse.class, "getFileName", "setFileName" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", XLSOutputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_separator] = new PropertyDescriptor ( "separator", XLSOutputSynapse.class, "getSeparator", "setSeparator" ); properties[PROPERTY_separator].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", XLSOutputSynapse.class, "getName", "setName" ); properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", XLSOutputSynapse.class, "getMonitor", "setMonitor" ); properties[PROPERTY_monitor].setExpert ( true ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
/* * StreamInputSynapseBeanInfo.java * * Created on 21 maggio 2004, 19.51 */ package org.joone.io; import java.beans.*; /** * @author paolo */ public class StreamInputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( StreamInputSynapse.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedColumnSelector = 0; private static final int PROPERTY_buffered = 1; private static final int PROPERTY_decimalPoint = 2; private static final int PROPERTY_enabled = 3; private static final int PROPERTY_firstRow = 4; private static final int PROPERTY_inputPatterns = 5; private static final int PROPERTY_lastRow = 6; private static final int PROPERTY_maxBufSize = 7; private static final int PROPERTY_name = 8; private static final int PROPERTY_stepCounter = 9; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[10]; try { properties[PROPERTY_advancedColumnSelector] = new PropertyDescriptor ( "advancedColumnSelector", StreamInputSynapse.class, "getAdvancedColumnSelector", "setAdvancedColumnSelector" ); properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", StreamInputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_decimalPoint] = new PropertyDescriptor ( "decimalPoint", StreamInputSynapse.class, "getDecimalPoint", "setDecimalPoint" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", StreamInputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_firstRow] = new PropertyDescriptor ( "firstRow", StreamInputSynapse.class, "getFirstRow", "setFirstRow" ); properties[PROPERTY_inputPatterns] = new PropertyDescriptor ( "inputPatterns", StreamInputSynapse.class, "getInputPatterns", "setInputPatterns" ); properties[PROPERTY_inputPatterns].setExpert ( true ); properties[PROPERTY_lastRow] = new PropertyDescriptor ( "lastRow", StreamInputSynapse.class, "getLastRow", "setLastRow" ); properties[PROPERTY_maxBufSize] = new PropertyDescriptor ( "maxBufSize", StreamInputSynapse.class, "getMaxBufSize", "setMaxBufSize" ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", StreamInputSynapse.class, "getName", "setName" ); properties[PROPERTY_stepCounter] = new PropertyDescriptor ( "stepCounter", StreamInputSynapse.class, "isStepCounter", "setStepCounter" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods private static final int METHOD_addNoise0 = 0; private static final int METHOD_canCountSteps1 = 1; private static final int METHOD_check2 = 2; private static final int METHOD_fwdGet3 = 3; private static final int METHOD_fwdPut4 = 4; private static final int METHOD_gotoFirstLine5 = 5; private static final int METHOD_gotoLine6 = 6; private static final int METHOD_initLearner7 = 7; private static final int METHOD_InspectableTitle8 = 8; private static final int METHOD_Inspections9 = 9; private static final int METHOD_numColumns10 = 10; private static final int METHOD_randomize11 = 11; private static final int METHOD_readAll12 = 12; private static final int METHOD_reset13 = 13; private static final int METHOD_resetInput14 = 14; private static final int METHOD_revGet15 = 15; private static final int METHOD_revPut16 = 16; private static final int METHOD_setPlugin17 = 17; // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[18]; try { methods[METHOD_addNoise0] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("addNoise", new Class[] {Double.TYPE})); methods[METHOD_addNoise0].setDisplayName ( "" ); methods[METHOD_canCountSteps1] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("canCountSteps", new Class[] {})); methods[METHOD_canCountSteps1].setDisplayName ( "" ); methods[METHOD_check2] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("check", new Class[] {})); methods[METHOD_check2].setDisplayName ( "" ); methods[METHOD_fwdGet3] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("fwdGet", new Class[] {})); methods[METHOD_fwdGet3].setDisplayName ( "" ); methods[METHOD_fwdPut4] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("fwdPut", new Class[] {org.joone.engine.Pattern.class})); methods[METHOD_fwdPut4].setDisplayName ( "" ); methods[METHOD_gotoFirstLine5] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("gotoFirstLine", new Class[] {})); methods[METHOD_gotoFirstLine5].setDisplayName ( "" ); methods[METHOD_gotoLine6] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("gotoLine", new Class[] {Integer.TYPE})); methods[METHOD_gotoLine6].setDisplayName ( "" ); methods[METHOD_initLearner7] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("initLearner", new Class[] {})); methods[METHOD_initLearner7].setDisplayName ( "" ); methods[METHOD_InspectableTitle8] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("InspectableTitle", new Class[] {})); methods[METHOD_InspectableTitle8].setDisplayName ( "" ); methods[METHOD_Inspections9] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("Inspections", new Class[] {})); methods[METHOD_Inspections9].setDisplayName ( "" ); methods[METHOD_numColumns10] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("numColumns", new Class[] {})); methods[METHOD_numColumns10].setDisplayName ( "" ); methods[METHOD_randomize11] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("randomize", new Class[] {Double.TYPE})); methods[METHOD_randomize11].setDisplayName ( "" ); methods[METHOD_readAll12] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("readAll", new Class[] {})); methods[METHOD_readAll12].setDisplayName ( "" ); methods[METHOD_reset13] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("reset", new Class[] {})); methods[METHOD_reset13].setDisplayName ( "" ); methods[METHOD_resetInput14] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("resetInput", new Class[] {})); methods[METHOD_resetInput14].setDisplayName ( "" ); methods[METHOD_revGet15] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("revGet", new Class[] {})); methods[METHOD_revGet15].setDisplayName ( "" ); methods[METHOD_revPut16] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("revPut", new Class[] {org.joone.engine.Pattern.class})); methods[METHOD_revPut16].setDisplayName ( "" ); methods[METHOD_setPlugin17] = new MethodDescriptor ( org.joone.io.StreamInputSynapse.class.getMethod("setPlugin", new Class[] {org.joone.util.ConverterPlugIn.class})); methods[METHOD_setPlugin17].setDisplayName ( "" ); } catch( Exception e) {}//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.io.*; public class StreamInputFactory { public StreamInputFactory() {} public StreamInputSynapse getInput(String streamName) throws IOException { if ((streamName.startsWith("http://")) || (streamName.startsWith("ftp://"))) { URLInputSynapse uis = new URLInputSynapse(); uis.setURL(streamName); return uis; } else { FileInputSynapse fis = new FileInputSynapse(); fis.setInputFile(new File(streamName)); return fis; } } }
Java
/* * InputConnector.java * * Created on September 15, 2004, 2:34 PM */ package org.joone.io; import java.util.*; import org.joone.engine.*; import org.joone.log.*; import org.joone.util.*; import org.joone.net.NetCheck; /** * * @author drmarpao */ public class InputConnector extends StreamInputSynapse implements PlugInListener { /** Logger for this class. */ private static final ILogger log = LoggerFactory.getLogger(InputConnector.class); private static final long serialVersionUID = -3316265583123866079L; /** The input stream this connector is connected to. */ private StreamInputSynapse inputSynapse; /** Creates a new instance of InputConnector */ public InputConnector() { setBuffered(false); } protected void initInputStream() throws org.joone.exception.JooneRuntimeException { currentRow = getFirstRow(); EOF = false; } /** * Attach a <code>StreamInputSynapse</code> to this connector. * * @param input the <code>StreamInputSynapse</code> to attach. <code>null</code> * to free this connector */ public boolean setInputSynapse(StreamInputSynapse input) { if (input != null) { input.setMonitor(getMonitor()); input.setBuffered(true); input.setStepCounter(false); input.setInputFull(true); input.addPlugInListener(this); setOutputFull(true); } else { setOutputFull(false); if (inputSynapse != null) { inputSynapse.removePlugInListener(this); inputSynapse.setInputFull(false); } } inputSynapse = input; return true; } protected Pattern getStream() { if (inputSynapse == null) return null; Pattern patt = inputSynapse.fwdGet(this); if (patt != null) { if (cols == null) setColList(); if (cols == null) return null; // In this case we cannot continue inps = new double[cols.length]; for (int x = 0; x < cols.length; ++x) { inps[x] = patt.getArray()[cols[x] - 1]; } // Calculates the new current line // and check the EOF ++currentRow; if (currentRow - getFirstRow() > (getMonitor().getNumOfPatterns() - 1)) EOF = true; if ((getLastRow() > 0) && (getCurrentRow() > getLastRow())) EOF = true; forward(inps); Pattern newPattern = new Pattern(outs); newPattern.setCount(getCurrentRow() - getFirstRow()); return newPattern; } else return null; } public void setMonitor(Monitor newMonitor) { super.setMonitor(newMonitor); if (inputSynapse != null) inputSynapse.setMonitor(newMonitor); } public void dataChanged(PlugInEvent anEvent) { // data has changed so by removing all elements (changed) data will be // retrieved again from the underlying stream input if (isBuffered()) { getInputVector().removeAllElements(); } } public java.util.TreeSet check() { TreeSet checks = super.check(); // Check that the first row is greater than 0. if (inputSynapse == null) { checks.add(new NetCheck(NetCheck.FATAL, "Input Synapse not set", this)); } else if (!inputSynapse.isBuffered()) { checks.add(new NetCheck(NetCheck.FATAL, "The Input Synapse must be buffered", this)); } return checks; } public void resetInput() { if (inputSynapse != null) { inputSynapse.resetInput(); } } /** * Sets the current row. * Note : this method is needed by the MultipleInputSynpase. I wonder if it is * needed for any other purpose... So you probably don't need to use this method. * * @param aRow the new value for the current row. */ protected void setCurrentRow(int aRow) { currentRow = aRow; } }
Java
package org.joone.io; import java.util.*; import java.io.*; import org.joone.log.*; public class StreamInputTokenizer implements PatternTokenizer { /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(StreamInputTokenizer.class); private static final int MAX_BUFFER_SIZE = 1048576; // 1 MByte private LineNumberReader stream; private StringTokenizer tokenizer = null; private int numTokens = 0; private char m_decimalPoint = '.'; private String m_delim = "; \t\n\r\f"; private double[] tokensArray; private int maxBufSize; /** Creates new StreamInputTokenizer * @param in The input stream */ public StreamInputTokenizer(Reader in) throws java.io.IOException { this(in, MAX_BUFFER_SIZE); } /** Creates new StreamInputTokenizer * @param in The input stream * @param maxBufSize the max dimension of the input buffer */ public StreamInputTokenizer(Reader in, int maxBufSize) throws java.io.IOException { this.maxBufSize = maxBufSize; stream = new LineNumberReader(in, maxBufSize); stream.mark(maxBufSize); } /** Return the current line number. * @return the current line number */ public int getLineno() { return stream.getLineNumber(); } public int getNumTokens() throws java.io.IOException { return numTokens; } /** * Insert the method's description here. * Creation date: (17/10/2000 0.30.08) * @return float * @param posiz int */ public double getTokenAt(int posiz) throws java.io.IOException { if (tokensArray == null) if (!nextLine()) return 0; if (tokensArray.length <= posiz) return 0; return tokensArray[posiz]; } /** * Insert the method's description here. * Creation date: (17/10/2000 0.13.45) * @return float[] */ public double[] getTokensArray() { return tokensArray; } /** mark the current position. */ public void mark() throws java.io.IOException { stream.mark(maxBufSize); } /** Fetchs the next line and extracts all the tokens * @return false if EOF, otherwise true * @throws IOException if an I/O Error occurs */ public boolean nextLine() throws java.io.IOException { String line = stream.readLine(); if (line != null) { tokenizer = new StringTokenizer(line, m_delim, false); numTokens = tokenizer.countTokens(); if (tokensArray == null) tokensArray = new double[numTokens]; else if (tokensArray.length != numTokens) tokensArray = new double[numTokens]; for (int i = 0; i < numTokens; ++i) tokensArray[i] = nextToken(m_delim); return true; } else return false; } /** Return the next token's double value in the current line * @return the next double value */ private double nextToken() throws java.io.IOException { return this.nextToken(null); } /** Return the next token's double value in the current line; * tokens are separated by the characters contained in delim * @return the next double value * @param delim String containing the delimitators characters */ private double nextToken(String delim) throws java.io.IOException { double v; String nt = null; if (tokenizer == null) nextLine(); if (delim != null) nt = tokenizer.nextToken(delim); else nt = tokenizer.nextToken(); if (m_decimalPoint != '.') nt = nt.replace(m_decimalPoint, '.'); try { v = Double.valueOf(nt).floatValue(); } catch (NumberFormatException nfe) { log.warn("Warning: Not numeric value at row "+getLineno()+": <" + nt + ">"); v = 0; } return v; } /** Go to the last marked position. Begin of input stream if no mark detected. */ public void resetInput() throws java.io.IOException { stream.reset(); tokenizer = null; } public void setDecimalPoint(char dp) { m_decimalPoint = dp; } public char getDecimalPoint() { return m_decimalPoint; } }
Java
package org.joone.io; import java.beans.*; public class URLInputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( URLInputSynapse.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedColumnSelector = 0; private static final int PROPERTY_buffered = 1; private static final int PROPERTY_decimalPoint = 2; private static final int PROPERTY_enabled = 3; private static final int PROPERTY_firstRow = 4; private static final int PROPERTY_inputPatterns = 5; private static final int PROPERTY_lastRow = 6; private static final int PROPERTY_maxBufSize = 7; private static final int PROPERTY_monitor = 8; private static final int PROPERTY_name = 9; private static final int PROPERTY_plugIn = 10; private static final int PROPERTY_stepCounter = 11; private static final int PROPERTY_URL = 12; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[13]; try { properties[PROPERTY_advancedColumnSelector] = new PropertyDescriptor ( "advancedColumnSelector", URLInputSynapse.class, "getAdvancedColumnSelector", "setAdvancedColumnSelector" ); properties[PROPERTY_advancedColumnSelector].setDisplayName ( "Advanced Column Selector" ); properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", URLInputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_decimalPoint] = new PropertyDescriptor ( "decimalPoint", URLInputSynapse.class, "getDecimalPoint", "setDecimalPoint" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", URLInputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_firstRow] = new PropertyDescriptor ( "firstRow", URLInputSynapse.class, "getFirstRow", "setFirstRow" ); properties[PROPERTY_inputPatterns] = new PropertyDescriptor ( "inputPatterns", URLInputSynapse.class, "getInputPatterns", "setInputPatterns" ); properties[PROPERTY_inputPatterns].setExpert ( true ); properties[PROPERTY_lastRow] = new PropertyDescriptor ( "lastRow", URLInputSynapse.class, "getLastRow", "setLastRow" ); properties[PROPERTY_maxBufSize] = new PropertyDescriptor ( "maxBufSize", URLInputSynapse.class, "getMaxBufSize", "setMaxBufSize" ); properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", URLInputSynapse.class, "getMonitor", "setMonitor" ); properties[PROPERTY_monitor].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", URLInputSynapse.class, "getName", "setName" ); properties[PROPERTY_plugIn] = new PropertyDescriptor ( "plugIn", URLInputSynapse.class, "getPlugIn", "setPlugIn" ); properties[PROPERTY_plugIn].setExpert ( true ); properties[PROPERTY_stepCounter] = new PropertyDescriptor ( "stepCounter", URLInputSynapse.class, "isStepCounter", "setStepCounter" ); properties[PROPERTY_URL] = new PropertyDescriptor ( "URL", URLInputSynapse.class, "getURL", "setURL" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.beans.*; public class JDBCOutputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( JDBCOutputSynapse.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_buffered = 0; private static final int PROPERTY_dbURL = 1; private static final int PROPERTY_driverName = 2; private static final int PROPERTY_enabled = 3; private static final int PROPERTY_monitor = 4; private static final int PROPERTY_name = 5; private static final int PROPERTY_SQLAmendment = 6; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[7]; try { properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", JDBCOutputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_dbURL] = new PropertyDescriptor ( "dbURL", JDBCOutputSynapse.class, "getdbURL", "setdbURL" ); properties[PROPERTY_driverName] = new PropertyDescriptor ( "driverName", JDBCOutputSynapse.class, "getdriverName", "setdriverName" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", JDBCOutputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", JDBCOutputSynapse.class, "getMonitor", "setMonitor" ); properties[PROPERTY_monitor].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", JDBCOutputSynapse.class, "getName", "setName" ); properties[PROPERTY_SQLAmendment] = new PropertyDescriptor ( "SQLAmendment", JDBCOutputSynapse.class, "getSQLAmendment", "setSQLAmendment" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.io.*; import java.util.*; import org.joone.log.*; import org.apache.poi.hssf.usermodel.*; public class XLSInputTokenizer implements PatternTokenizer { /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(XLSInputTokenizer.class); private int numTokens = 0; private char m_decimalPoint = '.'; private double[] tokensArray; private int row_no = 0, mark_row = 0; final private HSSFSheet sheet; public XLSInputTokenizer(HSSFSheet i_sheet) throws java.io.IOException { sheet = i_sheet; } public int getLineno() { return row_no; }; public int getNumTokens() throws IOException { return numTokens; } public double getTokenAt(int p0) throws java.io.IOException { if (tokensArray == null) if (!nextLine()) return 0; if (tokensArray.length <= p0) return 0; return tokensArray[p0]; } public double[] getTokensArray() { return tokensArray; } public void mark() throws IOException { mark_row = row_no; } public boolean nextLine() throws IOException { int lastRowNum = sheet.getLastRowNum(); if (row_no <= lastRowNum){ HSSFRow row = sheet.getRow(row_no); if (row == null) { // The row doesn't exist (it's empty) numTokens = 0; tokensArray = new double[numTokens]; } else { int maxCol = 0; Hashtable cellist = new Hashtable(); Iterator iter = row.cellIterator(); while (iter.hasNext()) { double v = 0; HSSFCell cell = (HSSFCell)iter.next(); int i = cell.getCellNum(); if (i > maxCol) maxCol = i; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: String cellValue = (String)cell.getStringCellValue(); try { v = Double.valueOf(cellValue).doubleValue(); } catch (NumberFormatException nfe) { log.warn( "Warning: Not numeric cell at ("+row_no+","+i+"): <" + cellValue + "> - Skipping"); v = 0; } break; case HSSFCell.CELL_TYPE_NUMERIC: v = (double)cell.getNumericCellValue(); break; } cellist.put(new Integer(i), new Double(v)); } tokensArray = new double[maxCol+1]; Enumeration keys = cellist.keys(); while (keys.hasMoreElements()) { Integer Icol = (Integer)keys.nextElement(); Double Dval = (Double)cellist.get(Icol); tokensArray[Icol.intValue()] = Dval.doubleValue(); } } ++row_no ; return true; } else{ return false; } } public void resetInput() throws IOException { row_no = mark_row; } public void setDecimalPoint(char dp) { m_decimalPoint = dp; } public char getDecimalPoint() { return m_decimalPoint; } }
Java
/* * ImageOutputSynapse.java * * Created on 23 October 2005, 19:13 * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package org.joone.io; import java.awt.image.BufferedImage; import java.io.File; import java.util.TreeSet; import org.joone.log.*; import org.joone.net.NetCheck; /** * This class collects the output from the connected layer and places it into an image file. * Images can be produced in GIF, JPG and PNG formats. * <P> * <B>Colour Mode</B> * In colour mode ImageOutputSynapse expects seperate RGB input values in the range 0 to 1 from the * connected layer. So to produce an image of width 10 and height 10 there must be 10x10x3 inputs * from the previous layer/s. The red, green and blue components in the final image are set using the * individual component values from the input. * </P> * <P> * <B>Non Colour Mode / Grey Scale Mode </B> * In this mode the synapse treats each input value as a grey scale value for each pixel. In this mode * only Width*Height values are required. To produce the final image the Red, Green and Blue components * are the set to this same value. * </P> * @author Julien Norman */ public class ImageOutputSynapse extends StreamOutputSynapse { /** The object used when logging debug,errors,warnings and info. */ private static final ILogger log = LoggerFactory.getLogger(ImageOutputSynapse.class); static final long serialVersionUID = 1287752494948170142L; public final int JPG = 1; public final int GIF = 2; public final int PNG = 3; private String OutputDirectory = System.getProperty("user.dir"); private int ImageFileType = JPG; private int Width = 10; private int Height = 10; private boolean ColourMode = true; /** Creates a new instance of ImageOutputSynapse */ public ImageOutputSynapse() { } /** * Writes the Neural Network pattern to an Image file, the Image type is specified by * the ImageFileType property. */ public void write(org.joone.engine.Pattern pattern) { if ( pattern.getCount() != -1) { String formatName; switch(getImageFileType()) { case JPG : formatName = "jpg"; break; case GIF : formatName = "gif"; break; case PNG : formatName = "png"; break; default: formatName = "jpg"; } try { String outDir = getOutputDirectory(); if (!outDir.endsWith(System.getProperty("file.separator"))) outDir += System.getProperty("file.separator"); File theOutFile = new File(outDir+"Image"+pattern.getCount()+"."+formatName); BufferedImage outImage = patternToImage(pattern); if ( outImage != null) { javax.imageio.ImageIO.write(outImage, formatName, theOutFile); } } catch(Exception ex) { log.error("Caught exception when trying to write Image : "+ex.toString()); } } } /** * Converts the given Neural Network pattern to a BufferedImage. * @param pat The Neural Network pattern to convert. * @return The pattern converted to a BufferedImage. */ private BufferedImage patternToImage(org.joone.engine.Pattern pat) { BufferedImage theImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); double [] array = pat.getArray(); int Red = 0,Green= 0,Blue = 0; int rgb = 0, x=0, y=0, j=0; if ( ColourMode ) { if ( array.length == getWidth()*getHeight()*3) { //for ( y=0;y<getHeight();y++) // for ( x=0;x<getWidth()*3;x+=3) { for ( j=0;j<array.length;j+=3){ Red = (int)(array[j]*255.0); Green = (int)(array[j+1]*255.0); Blue = (int)(array[j+2]*255.0); rgb = 0 + (Red<<16) + (Green<<8) + Blue; theImage.setRGB(x,y,rgb); x++; if ( x >= getWidth()) { x=0; y++; } } } else { log.error("Pattern Contains "+pat.getCount()+" RGB Values - Image Contains "+(getWidth()*getHeight())+" RGB Values , Size Mismatch."); } } else { if ( array.length == getWidth()*getHeight()) { for ( j=0;j<array.length;j++){ rgb = (int)(array[j]*(double)255); rgb = 0 + (rgb << 16) + (rgb << 8) + rgb; theImage.setRGB(x,y,rgb); x++; if ( x >= getWidth()) { x=0; y++; } } } else { log.error("Pattern Contains "+pat.getCount()+" RGB Values - Image Contains "+(getWidth()*getHeight())+" RGB Values , Size Mismatch."); } } return(theImage); } /** * Gets the directory where Image files will be created. */ public String getOutputDirectory() { return OutputDirectory; } /** * Sets the name of the directory where Image files will be created. * @param OutputDirectory The directory used to store generated image files. */ public void setOutputDirectory(String OutputDirectory) { this.OutputDirectory = OutputDirectory; } /** * Obtains the image type JPG = 1, GIF = 2, PNG = 3 of the format of the output files. */ public int getImageFileType() { return ImageFileType; } /** * Sets the image type JPG = 1, GIF = 2, PNG = 3 of the format of the generated image files. * @param ImageFileType JPG = 1, GIF = 2, PNG = 3. */ public void setImageFileType(int ImageFileType) { this.ImageFileType = ImageFileType; if ( this.ImageFileType < 1) this.ImageFileType = 1; if ( this.ImageFileType > 3) this.ImageFileType = 3; } /** * Gets the desired width of the generated image files. */ public int getWidth() { return Width; } /** * Sets the desired width of the generated image files. */ public void setWidth(int Width) { this.Width = Width; } /** * Gets the desired height of the generated image files. */ public int getHeight() { return Height; } /** * Sets the desired height of the generated image files. */ public void setHeight(int Height) { this.Height = Height; } /** * Determines if this synapse is in colour mode. false if in grey scale mode. * @return The ColourMode if this synapse. */ public boolean getColourMode() { return ColourMode; } /** * Sets the colour mode of this synapse. * @param ColourMode true if in colour mode, false if in grey scale mode. */ public void setColourMode(boolean ColourMode) { this.ColourMode = ColourMode; } /** Checks and returns any problems found with the settings of this synapse. * @return A TreeSet of problems or errors found with this synapse. */ public TreeSet check() { TreeSet checks = super.check(); if (ColourMode ) { if (Width*Height*3 != this.getInputDimension()) { checks.add(new NetCheck(NetCheck.FATAL, "Image Width["+getWidth()+"]*Height["+getHeight()+"]*3 not equal to number of inputs from connected layer/s ["+this.getInputDimension()+"]." , this)); } } else { if (Width*Height != this.getInputDimension()) { checks.add(new NetCheck(NetCheck.FATAL, "Image Width["+getWidth()+"]*Height["+getHeight()+"] not equal to number of inputs from connected layer/s ["+this.getInputDimension()+"]." , this)); } } if ( OutputDirectory.equals("") ) { checks.add(new NetCheck(NetCheck.FATAL, "No image output directory set." , this)); } return checks; } }
Java
package org.joone.io; import java.io.*; import java.text.*; import java.net.URL; import java.util.*; import org.joone.log.*; import org.joone.net.NetCheck; import org.joone.exception.JooneRuntimeException; import org.joone.engine.NetErrorManager; /** * <P>The YahooFinanceInputSynapse provides support for financial data input from financial markets. The * synapse contacts YahooFinance services and downloads historical data for the chosen symbol and date range. * Finally the data is presented to the network in reverse date order i.e oldest first. </P> * <P>This synapse provides the following info .. </P> * <P>Open as column 1</P> * <P>High as column 2</P> * <P>Low as column 3</P> * <P>Close as column 4.</P> * <P>Volume as column 5.</P> * <P>Adj.Close as column 6.</P> * <P>For the particular stock symbol.</P> * <BR> * <P> Developer Notes : </P> * <P> This YahooFinanceInputSynapse uses the following format to extract stock financial information from the Yahoo Network</P>. * <P>http://table.finance.yahoo.com/table.csv?a=8&b=1&c=2002&d=11&e=3&f=2002&s=tsco.l&y=0&g=d&ignore=.csv</P> * <BR> * <P>a = From Month 0 - 11</P> * <P>b = From Day 1-31</P> * <P>c = From Year XXXX</P> * <P>d = To Month 0-11</P> * <P>e = To Day 1-31</P> * <P>f = To Year XXXX</P> * <P>s = Symbol</P> * <P>y = [record] from record to + 200 records</P> * <P>g=[d] or[m] or [y] - daily or monthly or yearly</P> * <P>ignore = .csv</P> * */ public class YahooFinanceInputSynapse extends StreamInputSynapse { /** The object used when logging debug,errors,warnings and info. */ private static final ILogger log = LoggerFactory.getLogger(YahooFinanceInputSynapse.class); String [] months = new String [] {"January","February","March","April","May","June","July","August","September","October","November","December"}; String [] frequency = new String [] {"Daily","Weekly","Monthly"}; String [] freq_conv = new String [] {"d","w","m"}; String Symbol = new String(""); DateFormat date_formater = DateFormat.getDateInstance(DateFormat.MEDIUM); Calendar CalendarStart = Calendar.getInstance(); Calendar CalendarEnd = Calendar.getInstance(); String DateStart = new String(date_formater.format(CalendarStart.getTime())); String DateEnd = new String(date_formater.format(CalendarEnd.getTime())); String Period = new String("Daily"); private transient Date startDate = CalendarStart.getTime(); private transient Date endDate = CalendarEnd.getTime(); private Vector StockData [] = new Vector [6]; // Holds all the data + optional data, oldest first. private Vector StockDates = new Vector(); // Holds the Dates associated with each row of data. String [] ColumnNames = new String [] {"Date","Open","High","Low","Close","Volume","Adj. Close"}; // Ignore lines with these names in static final long serialVersionUID = 1301769209320717393L; /** * Constructor for the YahooFinanceInputSynapse object */ public YahooFinanceInputSynapse() { super(); } /** * Gets the name of the symbol * * @return The Symbol name */ public String getSymbol() { return Symbol; } /** * Gets year to start data retrieval from. * * @return The year to start from * @deprecated Use getStartDate instead */ public String getDateStart() { return DateStart; } /** * Gets year to end data retrieval from * * @return The year to end on * @deprecated Use getEndDate instead */ public String getDateEnd() { return DateEnd; } /** * Gets the period for data retrieval. * * @return The month to end on */ public String getPeriod() { return Period; } /** * Gets the dates associated with each row of data. */ public Vector getStockDates() { return(StockDates); } /** * <P>Gets the stock data retrieived by this synapse. Returns the data in a Vector array of length 5.</P> * <P>In column 0 Open data.</P> * <P>In column 1 High</P> * <P>In column 2 Low</P> * <P>In column 3 Close</P> * <P>In column 4 Volume</P> * <P>In column 5 Adj.Close</P> * */ public Vector [] getStockData() { return(StockData); } /** * Reads this YahooFinanceInputSynapse object into memory from the specified object stream. * * @param in The object input stream that this object should be read from * @exception IOException The Input Output Exception * @exception ClassNotFoundException The class not found exception */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { super.readObjectBase(in); if (in.getClass().getName().indexOf("xstream") == -1) { Symbol = (String) in.readObject(); DateStart = (String) in.readObject(); DateEnd = (String) in.readObject(); Period = (String) in.readObject(); } if (!isBuffered() || (getInputVector().size() == 0)) { initInputStream(); } try { startDate = date_formater.parse(DateStart); endDate = date_formater.parse(DateEnd); } catch (ParseException ex) { log.error("Invalid Date: start:"+DateStart+" end:"+DateEnd); } } /** * Sets the name of the database jdbc driver. * * @param newSymbol The new stock symbol to retrieve the data with. * @deprecated Use setEndDate instead */ public void setSymbol(java.lang.String newSymbol) { // Only set if it actually has changed if ( !Symbol.equals(newSymbol)) { Symbol = newSymbol; this.resetInput(); this.setTokens(null); } } /** * Gets the the data from which data is retrieved. * * @param newDataStart The data from which data is retrieved. * @deprecated Use setStartDate instead */ public void setDateStart(String newDateStart) { // Only set if it actually has changed if (!DateStart.equals(newDateStart)) { DateStart = newDateStart; this.resetInput(); this.setTokens(null); } } /** * Gets the the data to which data is retrieved. * * @param newDateEnd The date to which data is retrieved. */ public void setDateEnd(String newDateEnd) { // Only set if it actually has changed if (!DateEnd.equals(newDateEnd)) { DateEnd = newDateEnd; this.resetInput(); this.setTokens(null); } } /** * Sets the period with which to retrieve data should be one of "Daily" or "Monthly" or "Yearly". * * @param newPeriod The period with which data is retieved. */ public void setPeriod(String newPeriod) { // Only set if it actually has changed if (!Period.equals(newPeriod)) { Period = newPeriod; this.resetInput(); this.setTokens(null); } } /** * Writes this YahooFInanceSynapseInput object to the ObjectOutputStream out. * * @param out The ObjectOutputSteeam that this object should be written to * @exception IOException The Input Output Exception if any */ private void writeObject(ObjectOutputStream out) throws IOException { super.writeObjectBase(out); if (out.getClass().getName().indexOf("xstream") == -1) { out.writeObject(Symbol); out.writeObject(DateStart); out.writeObject(DateEnd); out.writeObject(Period); } } /** * Connects to Yahoo FInancial Services and obtains the historical data for the specifed symbol and data range. */ protected void initInputStream() throws JooneRuntimeException { String final_patterns = new String(""); // A buffer of final_patterns to present to the Tokenizer int start=0; String myUrl = new String(""); // Used to construct the URL to obtain the data String cperiod = "d"; // Default char period to 'd' for Daily for ( int i=0;i<frequency.length;i++) { if ( Period.equals(frequency[i]) ) cperiod = freq_conv[i]; // Get the period character d,w or m } StockData = null; StockDates = null; if ((Symbol != null) && (!Symbol.equals(new String("")))) { try { CalendarStart = Calendar.getInstance(); CalendarEnd = Calendar.getInstance(); CalendarStart.setTime( date_formater.parse(DateStart) ); CalendarEnd.setTime( date_formater.parse(DateEnd) ); } catch ( ParseException ex ) { // Could not parse one of the date strings. log.error( "YahooFinanceInputSynapse could not parse date string. Message is : = "+ex.getMessage()); // LOG4J CalendarStart = null; CalendarEnd = null; //throw new JooneRuntimeException(ex.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"YahooFinanceInputSynapse could not parse date string. "+ex.getMessage()); return; } int addedData = 1; if (CalendarStart != null) { if (CalendarEnd != null) { if (Period != null) { log.info("Contacting Yahoo Finance Network."); try { while ((addedData > 0) && (addedData <= 200)) { myUrl = new String("http://table.finance.yahoo.com/table.csv?a="+CalendarStart.get(Calendar.MONTH)+"&b="+CalendarStart.get(Calendar.DAY_OF_MONTH)+"&c="+CalendarStart.get(Calendar.YEAR)+"&d="+CalendarEnd.get(Calendar.MONTH)+"&e="+CalendarEnd.get(Calendar.DAY_OF_MONTH)+"&f="+CalendarEnd.get(Calendar.YEAR)+"&s="+Symbol+"&g="+cperiod+"&z=200&y="+start+"&ignore=.csv"); addedData = addURLToMemory(new URL(myUrl)); start += 200; } } catch ( IOException ex ) { log.error( "Error obtaining data from YahooFInance. Error message is "+ex.getMessage()); //throw new JooneRuntimeException(ex.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Error obtaining data from YahooFInance."+ex.getMessage()); return; } log.info("Loaded Yahoo Fianance data ok."); // Compose final pattern to give to network, also give in reverse order so oldest date first for ( int i=StockData[0].size()-1;i>=0;i--) { // OPEN final_patterns += ((Double)StockData[0].elementAt(i)).toString(); // HIGH final_patterns += ";"+((Double)StockData[1].elementAt(i)).toString(); // LOW final_patterns += ";"+((Double)StockData[2].elementAt(i)).toString(); // CLOSE final_patterns += ";"+((Double)StockData[3].elementAt(i)).toString(); // VOLUME final_patterns += ";"+((Double)StockData[4].elementAt(i)).toString(); // ADJ. CLOSE final_patterns += ";"+((Double)StockData[5].elementAt(i)).toString(); final_patterns += '\n'; } try{ StreamInputTokenizer sit; if (getMaxBufSize() > 0) sit = new StreamInputTokenizer(new StringReader(final_patterns), getMaxBufSize()); else sit = new StreamInputTokenizer(new StringReader(final_patterns)); super.setTokens(sit); } catch (IOException ex) { // Use Log4j log.error( "IOException thrown while initializing the YahooFinanceInputStream. Message is : " + ex.getMessage()); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Error while trying to parse Yahoo Finance data. Message is : "+ex.getMessage()); } } // End of if period is null } // End if not Year Start } // End if not Day Start } // end if no Symbol } // End method initInputStream /** * Adds data from a URL in CSV format to Memory * @return the number of lines added to the buffer */ private int addURLToMemory(URL Data) throws IOException { LineNumberReader url_reader = null; String Line = new String(""); boolean IgnoreHeader = true; boolean added_data = true; boolean Docontinue = true; log.debug(Data.getProtocol()+"://"+Data.getHost()+Data.getFile()); int initSize = 0; // Check that the URL is not null if ( Data != null) { url_reader = new LineNumberReader(new InputStreamReader(new BufferedInputStream(Data.openStream()))); // Read the first line Line = url_reader.readLine(); if ( StockDates == null)StockDates = new Vector(); if ( (StockData == null)||(StockData.length < 6))StockData = new Vector[6]; // Init Pattern list if ( StockData[0] == null )StockData[0] = new Vector(); // Open if ( StockData[1] == null )StockData[1] = new Vector(); // High if ( StockData[2] == null )StockData[2] = new Vector(); // Low if ( StockData[3] == null )StockData[3] = new Vector(); // Close if ( StockData[4] == null )StockData[4] = new Vector(); // Volume if ( StockData[5] == null )StockData[5] = new Vector(); // Adj.Close initSize = StockData[0].size(); while ( (Line != null) && (!Line.equals("")) && (Docontinue == true)) { if ( IgnoreHeader == true) // Just throw header line away { if ( Line.indexOf(ColumnNames[0]) < 0) { if ( Line.indexOf(",")!=-1 ) // Check for bad data { StringTokenizer tokens = new StringTokenizer(Line, ",\n"); if (tokens.countTokens() >= 7) { added_data = true; String _data = tokens.nextToken(); StockDates.addElement(_data); // Get Stock Date for row // log.debug(_data); StockData[0].add(Double.valueOf(tokens.nextToken())); // Add OPEN to pattern vector StockData[1].add(Double.valueOf(tokens.nextToken())); // Add HIGH to pattern vector StockData[2].add(Double.valueOf(tokens.nextToken())); // Add LOW to pattern vector StockData[3].add(Double.valueOf(tokens.nextToken())); // Add CLOSE to pattern vector StockData[4].add(Double.valueOf(tokens.nextToken())); // Add VOLUME to pattern vector StockData[5].add(Double.valueOf(tokens.nextToken())); // Add Adj.Close to pattern vector } } // End check for bad data else Docontinue = false; } } Line = url_reader.readLine(); } } int addedData = StockData[0].size() - initSize; //if ( url_reader != null) // if ( url_reader.getLineNumber() <= 2) added_data=false; // Consider the data not added if only one line of data return addedData; } // End Add URL To Memory /** * Check that there are no errors or problems with the properties of this YahooFinanceInputSynapse. * @return The TreeSet of errors / problems if any. */ public TreeSet check() { TreeSet checks = super.check(); if ( (getDateStart() != null) && (!getDateStart().equals("")) ) { try { date_formater.parse(DateStart); } catch ( ParseException ex ) { checks.add(new NetCheck(NetCheck.FATAL, "Format for Start Date is invalid." , this)); } } else checks.add(new NetCheck(NetCheck.FATAL, "Start Date should be populated." , this)); if ( (getDateEnd() != null) && (!getDateEnd().equals("")) ) { try { date_formater.parse(DateEnd); } catch ( ParseException ex ) { checks.add(new NetCheck(NetCheck.FATAL, "Format for End Date is invalid." , this)); } } else checks.add(new NetCheck(NetCheck.FATAL, "End Date should be populated." , this)); if ( getPeriod()!=null) { if ( !getPeriod().equals("Daily") && !getPeriod().equals("Weekly") && !getPeriod().equals("Monthly") ) { checks.add(new NetCheck(NetCheck.FATAL, "Period should be one of 'Daily' , 'Weekly' , 'Monthly'." , this)); } } else checks.add(new NetCheck(NetCheck.FATAL, "Period should be one of 'Daily' , 'Weekly' , 'Monthly'." , this)); if ( (getSymbol()== null)||(getSymbol().equals(""))) checks.add(new NetCheck(NetCheck.FATAL, "Symbol should be populated." , this)); return checks; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; DateStart = new String(date_formater.format(startDate)); this.resetInput(); this.setTokens(null); } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; DateEnd = new String(date_formater.format(endDate)); this.resetInput(); this.setTokens(null); } }
Java
package org.joone.io; import java.beans.*; public class FileOutputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor private static BeanDescriptor beanDescriptor = new BeanDescriptor ( FileOutputSynapse.class , null ); private static BeanDescriptor getBdescriptor(){ return beanDescriptor; } static {//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_append = 0; private static final int PROPERTY_separator = 1; private static final int PROPERTY_name = 2; private static final int PROPERTY_buffered = 3; private static final int PROPERTY_fileName = 4; private static final int PROPERTY_enabled = 5; private static final int PROPERTY_monitor = 6; // Property array private static PropertyDescriptor[] properties = new PropertyDescriptor[7]; private static PropertyDescriptor[] getPdescriptor(){ return properties; } static { try { properties[PROPERTY_append] = new PropertyDescriptor ( "append", FileOutputSynapse.class, "isAppend", "setAppend" ); properties[PROPERTY_separator] = new PropertyDescriptor ( "separator", FileOutputSynapse.class, "getSeparator", "setSeparator" ); properties[PROPERTY_separator].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", FileOutputSynapse.class, "getName", "setName" ); properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", FileOutputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_fileName] = new PropertyDescriptor ( "fileName", FileOutputSynapse.class, "getFileName", "setFileName" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", FileOutputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", FileOutputSynapse.class, "getMonitor", "setMonitor" ); properties[PROPERTY_monitor].setExpert ( true ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array private static EventSetDescriptor[] eventSets = new EventSetDescriptor[0]; private static EventSetDescriptor[] getEdescriptor(){ return eventSets; } //GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. //GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array private static MethodDescriptor[] methods = new MethodDescriptor[0]; private static MethodDescriptor[] getMdescriptor(){ return methods; } //GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. //GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return beanDescriptor; } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return properties; } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return eventSets; } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return methods; } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.io.*; import java.sql.*; import java.util.*; import org.joone.net.NetCheck; import org.joone.exception.JooneRuntimeException; import org.joone.engine.NetErrorManager; import org.joone.log.*; /** * <P>The JDBCOutputSynapse provides support for data input to a database. * To use this synapse the user should ensure a JDBC Type 4 Driver is in the class path. * It is possible to use other JDBC driver types though you will have to refer to the vendors documentation, * it may require extra software insallation and this may limit your distributtion to certain Operating Systems.</P> * <P>The properties required by this JDBCOutputSynapse Plugin are the following</P> * <P>Database Driver Name - e.g sun.jdbc.odbc.JdbcOdbcDriver</P> * <P>Database URL - e.g jdbc:mysql://localhost/MyDb?user=myuser&password=mypass * <P>SQLAmendment - e.g "INSERT INTO MY_RESULT_TABLE (RESULT1,RESULT2) VALUES(JOONE[1],JOONE[2])" where JOONE[1] is the first value of the current output.</P> * <P>Note : The database URL uses specific protocol after the "jdbc:" section check with the jdbc driver vendor for specific info.</P> * <P>Some commonly used Driver protocols shown below ...</P> * <BR> * <P>Driver {com.mysql.jdbc.Driver} </P> * <P>Protocol {jdbc:mysql://[hostname][,failoverhost...][:port]/[dbname][?param1=value1][&param2=value2].....} MySQL Protool </P> * <P>Example {jdbc:mysql://localhost/test?user=blah&password=blah} </P> * <P>Web Site {http://www.mysql.com} </P> * <BR> * <P>Driver {sun.jdbc.odbc.JdbcOdbcDriver} </P> * <P>Protocol { jdbc:odbc:<data-source-name>[;<attribute-name>=<attribute-value>]* } ODBC Protocol </P> * <P>Example {jdbc:odbc:mydb;UID=me;PWD=secret} </P> * <P>Web Site {http://www.java.sun.com} </P> * <BR> * <P>Data Types</P> * <BR> * <P>Any fields receiving a value should be able to contain a single double. The * data type is not so important it can be text or a number field so long as can hold a double value.</P> * * @author Julien Norman */ public class JDBCOutputSynapse extends StreamOutputSynapse { /** The object used when logging debug,errors,warnings and info. */ private static final ILogger log = LoggerFactory.getLogger(JDBCOutputSynapse.class); /** The name of the JDBC Database driver. */ private String driverName = ""; /** The URL of the database. */ private String dbURL = ""; /** The database query to use in order to obtain the input data. */ private String SQLAmendment = ""; private transient Connection con = null; private transient Statement stmt = null; private static final long serialVersionUID = 2176832390164459511L; /** *Constructor for the JDBCOutputSynapse object */ public JDBCOutputSynapse() { super(); } /** * <P>Constructor for the JDBCInputSynapse object that allows all options. * Allows the user to construct a JDBCInputSynapse in one call.</P> * @param newDrivername The class name of the database driver to use. * @param newdbURL The Universal Resource Locator to enable connection to the database. * @param newSQLAmendment The database SQL amendment to apply to the database. * @param buffered Whether this synapse is buffered or not. */ public JDBCOutputSynapse(String newDrivername, String newdbURL, String newSQLAmendment, boolean buffered) { super(); setBuffered(buffered); setdriverName(newDrivername); setdbURL(newdbURL); setSQLAmendment(newSQLAmendment); } /** * Gets the name of the database jdbc driver used by this JDBC input syanpse. * * @return The JDBC Driver name */ public java.lang.String getdriverName() { return driverName; } /** * Gets the name of the database Universal Resource Location (URL) * * @return The database URL used by this JDBC input syanpse. */ public java.lang.String getdbURL() { return dbURL; } /** * Gets the SQL Query used to select data from the database. * * @return The SQLAmendment used by this JDBC input syanpse. */ public java.lang.String getSQLAmendment() { return SQLAmendment; } /** * Sets the name of the database jdbc driver. * * @param newDriverName The JDBC Driver name */ public void setdriverName(java.lang.String newDriverName) { // Check that it's actually changed. if (!newDriverName.equals(driverName)) { driverName = newDriverName; } } /** * Gets the name of the database Universal Resource Location (URL) * * @param newdbURL The database URL to use for selecting input. See the notes on this class for usage. */ public void setdbURL(java.lang.String newdbURL) { // Check it's actually changed. if (!dbURL.equals(newdbURL) ) { dbURL = newdbURL; } } /** * Sets the SQLAmendment attribute of the JDBCInputSynapse object * * @param newSQLAmendment The new database SQL Amendment. */ public void setSQLAmendment(java.lang.String newSQLAmendment) { // Check that it's actually changed. if (!SQLAmendment.equals(newSQLAmendment) ) { SQLAmendment = newSQLAmendment; } } /** * Connects to the database using Driver name and db URL and selects data using the SQLAmendment. */ protected void initStream() throws JooneRuntimeException { // This will contain pattern set // Ensure all properties have been set if ((driverName != null) && (!driverName.equals(new String("")))) { // Check that Driver Name has been set if ((dbURL != null) && (!dbURL.equals(new String("")))) { // Check that Database URL has been set if ((SQLAmendment != null) && (!SQLAmendment.equals(new String("")))) { // Check that SQLAmendment has been set try { Class.forName(driverName); // E.g sun.jdbc.odbc.JdbcOdbcDriver to use JDBC:ODBC bridge con = DriverManager.getConnection(dbURL); // URL if you have Fred ODBC Data source then e.g jdbc:odbc:Fred stmt = con.createStatement(); //ResultSet rs = stmt.executeQuery(SQLAmendment); } catch (ClassNotFoundException ex) { // Use Log4j log.error( "Could not find Database Driver Class while initializing the JDBCInputStream. Message is : " + ex.getMessage(), ex ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Could not find Database Driver Class while initializing the JDBCInputStream. Message is : " + ex.getMessage()); //System.out.println("Could not find Database Driver Class while initializing the JDBCInputStream. Message is : " + ex.getMessage()); // SYS LOG } catch (SQLException sqlex) { // Use Log4j log.error( "SQLException thrown while initializing the JDBCInputStream. Message is : " + sqlex.getMessage(), sqlex ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"SQLException thrown while initializing the JDBCInputStream. Message is : " + sqlex.getMessage()); //System.out.println("SQLException thrown while initializing the JDBCInputStream. Message is : " + sqlex.getMessage()); // SYS LOG } } else { // Warn the user or app that the SQLAmendment has not been set String err = "The SQL Amendment has not been entered!"; log.warn( err ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"The SQL Amendment has not been entered!"); } } else { // Warn the user or app that the Database URL has not been set String err = "The Database URL has not been entered!"; log.warn( err ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"The Database URL has not been entered!"); } } else { // Warn user or app that the Driver Name has not been set String err = "The Driver Name has not been entered!"; log.warn( err ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"The Driver Name has not been entered!"); } } /** * Check that parameters are set correctly for the this JDBCInputSynapse object. * * @see Synapse * @return validation errors. */ public TreeSet check() { // Get the parent's check messages. TreeSet checks = super.check(); Connection con; // To test the connection. // See if the driver name has been entered. if ((driverName == null)||(driverName.compareTo("")==0)) { checks.add(new NetCheck(NetCheck.FATAL, "Database Driver Name needs to be entered.", this)); } else { // Driver Name entered check that it is valid try { Class.forName(driverName); // Check driver class is correct E.g sun.jdbc.odbc.JdbcOdbcDriver to use JDBC:ODBC bridge // See if we can get a connection if there is a URL entered.... if ((dbURL != null)&&(dbURL.compareTo("")!=0)) { con = DriverManager.getConnection(dbURL); stmt = con.createStatement(); } } catch (ClassNotFoundException ex) { // Use Log4j checks.add(new NetCheck(NetCheck.FATAL, "Could not find Database Driver Class. Check Database Driver is in the classpath and is readable.",this)); // LOG4J } catch (SQLException sqlex) { checks.add(new NetCheck(NetCheck.FATAL, "The Database URL is incorrect. Connection error is : "+sqlex.toString(),this)); // LOG4J } } // Check that the dbURL has been entered. if ((dbURL == null)||(dbURL.compareTo("")==0)) { checks.add(new NetCheck(NetCheck.FATAL, "Database URL needs to be entered.", this)); } // Check that the SQLAmendment has been entered if ((SQLAmendment == null)||(SQLAmendment.compareTo("")==0)) { checks.add(new NetCheck(NetCheck.FATAL, "Database SQL Amendment needs to be entered.", this)); } return checks; } /** * Writes the pattern data to the database specified in the dbURL. The SQLAmendment proprty * should contain an SQL amendment using JOONE[X] to obtain the Xth pattern value where X=1 is the first value. * E.g. "INSERT INTO MY_RESULTS (RESULT1,RESULT2) VALUES('JOONE[1]','JOONE[2]')" * @param pattern The values to write to the database. */ public void write(org.joone.engine.Pattern pattern) throws JooneRuntimeException { String Amendment = new String(SQLAmendment); if ( (con == null) || (stmt==null) || (pattern.getCount() == 1)) initStream(); if ( pattern.getCount() == -1) { try{ if ( stmt != null) stmt.close(); if ( con != null) con.close(); } catch(SQLException ex) { stmt = null; con = null; } } else{ try{ if ( Amendment != null){ if ( !Amendment.equals("") ){ // Loop through pattern and replace each occurence of JOONE[X] with appropriate value for (int i=0; i < pattern.getArray().length; i++) { while ( Amendment.indexOf("JOONE["+(i+1)+"]")>=0) { // While we have a JOONE[i] string StringBuffer buf = new StringBuffer(Amendment); Amendment = buf.replace(Amendment.indexOf("JOONE["+(i+1)+"]") ,Amendment.indexOf("JOONE["+(i+1)+"]") + new String("JOONE["+(i+1)+"]").length(), new Double(pattern.getArray()[i]).toString()).toString(); } } // Ok we've replace the JOONE[X] strings with the correct values now execute the amendment. stmt.executeUpdate(Amendment); } } } catch(java.sql.SQLException ex){ String err = new String("An SQL error occurred while trying to execute ["+Amendment+"], error is "+ex.toString()); log.error( err ); // LOG4J if ( getMonitor() != null ) new NetErrorManager(getMonitor(),err); } } } }
Java
package org.joone.io; import java.io.*; import java.util.TreeSet; import org.joone.log.*; import org.apache.poi.poifs.filesystem.*; import org.apache.poi.hssf.usermodel.*; import org.joone.net.NetCheck; import org.joone.exception.JooneRuntimeException; import org.joone.engine.NetErrorManager; /** This class allows data to be presented to the network from an Excel XLS * formatted file. The XLS file name must be specified and a worksheet name is optional. */ public class XLSInputSynapse extends StreamInputSynapse { /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(XLSInputSynapse.class); /** The name of the XLS worksheet from the XLS file to be used as input data. */ private String i_sheet_name = ""; /** The internal HSSF workbook model to read XLS data into for presentation to the * network. */ private transient HSSFSheet i_sheet; /** The work sheet index number. */ private int i_sheet_index = 0; /** The default sheet index. */ /** The file input stream used to read the XLS file. */ private transient FileInputStream i_stream; private transient POIFSFileSystem i_fs; private transient HSSFWorkbook i_workbook; /** Flag to check the file name has been set. */ private boolean file_chk = false; // used to confirm if filname has been chosen yet /** The name of the XLS file to read data from. */ private String fileName = ""; private transient File inputFile; /** The serial ID of this object. */ private static final long serialVersionUID = 8625369117101456178L; /** The default constructor for this XLSInputSynapse. */ public XLSInputSynapse() { super(); } /** Gets the XLS file name used as input to the network. * @return The XLS input file name. * @deprecated use getInputFile instead */ public java.lang.String getFileName() { return fileName; } /** Sets the XLS file name that should be used to obtain input data from. * @param newFileName The XLS file name that should be used to obtain input data from. * @deprecated use setInputFile instead */ public void setFileName(java.lang.String newFileName) { if (!fileName.equals(newFileName)) { fileName = newFileName; file_chk = true; this.resetInput(); this.setTokens(null); //initInputStream(); } } /** Reads data from the XLS file into this synapse. */ protected void initInputStream() throws JooneRuntimeException { // check for sheet called j_input // get sheet number of j_output // get first available sheet if (new File(fileName).exists()) { if ((i_sheet = getSheet(i_sheet_name)) != null) try { super.setTokens(new XLSInputTokenizer(i_sheet)); } catch (IOException ioe) { log.error("Error creating XLSInputTokenizer. Message is : " + ioe.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Error creating XLSInputTokenizer. Message is : "+ioe.getMessage()); } } else { String err = "Excel XLS File '"+fileName+"' does not exist."; log.error(err); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Excel XLS File '"+fileName+"' does not exist."); } } /** Gets the HSSF sheet from the XLS file using the specified sheet name. * @return The HSSFSheet */ protected HSSFSheet getSheet(String sheetName) { HSSFSheet r_sheet = null; try { i_stream = new FileInputStream(fileName); i_fs = new POIFSFileSystem(i_stream); i_workbook = new HSSFWorkbook(i_fs); i_stream.close(); // Handle on workbook is now attained i_sheet_index = i_workbook.getSheetIndex(sheetName); //o_sheet_index = i_workbook.getSheetIndex("j_output"); if (i_sheet_index > -1) { r_sheet = i_workbook.getSheetAt(i_sheet_index); } else { /* if (o_sheet_index == 0) { r_sheet = i_workbook.getSheetAt(o_sheet_index + 1); } else { */ r_sheet = i_workbook.getSheetAt(0); } return r_sheet; } catch (IOException io_err) { log.error("Could not open worksheet '"+sheetName+"' from XLS file. Message is : " + io_err.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Could not open worksheet '"+sheetName+"' from XLS file. Message is : "+io_err.getMessage()); } return null; } /** Sets the name of the sheet within the XLS file to extract input data from. * @param sheetName The name of the sheet within the XLS file to extract input data from. */ public void setSheetName(String sheetName) { if (!i_sheet_name.equals(sheetName)) { i_sheet_name = sheetName; this.resetInput(); this.setTokens(null); /* if (file_chk) { if (i_workbook == null) // This is needed only to reinitialize all the transient variables getSheet(i_sheet_name); if (i_workbook.getSheetIndex(sheetName) != -1) { initInputStream(); } else { log.warn("Invalid input sheet name please choose another!"); } } else { log.warn("Please choose valid file first"); } */ } } /** Gets a list of available sheets from the XLS file. * @return The list of available sheets from the XLS file or null if the file name has not * been set. */ public String[] getAvailableSheetList() { int sheetCount = i_workbook.getNumberOfSheets(); String[] availableSheetList = null; for (int i = 0; i > sheetCount; i++) { availableSheetList[i] = i_workbook.getSheetName(i); } return availableSheetList; } /** Gets the name of the sheet within the XLS file to extract data from for input to * the network. * @return The name of the sheet within the XLS file to extract data from for input to * the network. */ public String getSheetName() { return i_sheet_name; } /** Reads this XLSInputSynpase object from the specified object stream. * @param in The object stream to read this XLSInputSynapse object from. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { super.readObjectBase(in); if (in.getClass().getName().indexOf("xstream") == -1) { fileName = (String) in.readObject(); } if (!isBuffered() || (getInputVector().size() == 0)) setFileName(fileName); if ((fileName != null) && (fileName.length() > 0)) inputFile = new File(fileName); } private void writeObject(ObjectOutputStream out) throws IOException { super.writeObjectBase(out); if (out.getClass().getName().indexOf("xstream") == -1) { out.writeObject(fileName); } } /** Returns a TreeSet of problems or errors with the setup of this XLSInputSynapse * object. * @return A TreeSet of problems or errors with the setup of this XLSInputSynapse * object. */ public TreeSet check() { TreeSet checks = super.check(); if (fileName == null || fileName.trim().equals("")) { checks.add(new NetCheck(NetCheck.FATAL, "File Name not set." , this)); } else { if (!getInputFile().exists()) { NetCheck error = new NetCheck(NetCheck.WARNING, "Input File doesn't exist." , this); if (getInputPatterns().isEmpty()) error.setSeverity(NetCheck.FATAL); checks.add(error); } } return checks; } public File getInputFile() { return inputFile; } public void setInputFile(File inputFile) { if (inputFile != null) { if (!fileName.equals(inputFile.getAbsolutePath())) { this.inputFile = inputFile; fileName = inputFile.getAbsolutePath(); file_chk = true; this.resetInput(); super.setTokens(null); } } else { this.inputFile = inputFile; fileName = ""; file_chk = true; this.resetInput(); super.setTokens(null); } } }
Java
/* * MemoryInputSynapse.java * * Created on 7 april 2002, 13.32 */ package org.joone.io; import org.joone.exception.JooneRuntimeException; /** * * @author pmarrone */ public class MemoryInputSynapse extends StreamInputSynapse { static final long serialVersionUID = 2066217695979040186L; private double[][] inputArray; /** Creates a new instance of MemoryInputSynapse */ public MemoryInputSynapse() { } protected void initInputStream() throws JooneRuntimeException { super.setTokens(new MemoryInputTokenizer(inputArray)); } /** Setter for property inputArray. * Use this method to initialize the input data * @param inputArray New value of property inputArray. */ public void setInputArray(double[][] inputArray) { this.inputArray = inputArray; initInputStream(); } }
Java
package org.joone.io; import java.io.*; import java.net.*; import org.joone.exception.JooneRuntimeException; import org.joone.log.*; import org.joone.engine.NetErrorManager; /** Allows data extraction from the internet or a file specified by a Universal * Resource Locator or URL. */ public class URLInputSynapse extends StreamInputSynapse { /** The logger used to log warning or errors. */ private static final ILogger log = LoggerFactory.getLogger(URLInputSynapse.class); /** The string of the URL used to extract input data. */ private String URL = "http://"; /** The actual URL used to extract input data. */ private URL cURL; private static final long serialVersionUID = -1871585397469526608L; /** The default constructor for this class. */ public URLInputSynapse() { super(); } /** Gets the URL used to extract input data from. * @return The URL used to extract input data from. */ public String getURL() { return URL; } /** Reads this URLInputSynapse object from the specified object stream. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { super.readObjectBase(in); if (in.getClass().getName().indexOf("xstream") == -1) { URL = (String) in.readObject(); } if (!isBuffered() || (getInputVector().size() == 0)) setURL(URL); } /** Sets the URL to extract input data from. * @param newURL The new URL used to extract input data from. */ public void setURL(java.lang.String newURL) { if (!URL.equals(newURL)) { this.resetInput(); this.setTokens(null); } //initInputStream(); } /** Writes this URLInputSynapse object into the specified object stream. */ private void writeObject(ObjectOutputStream out) throws IOException { super.writeObjectBase(out); if (out.getClass().getName().indexOf("xstream") == -1) { out.writeObject(URL); } } /** Reads the data from the URL specified in this URLInputSynapse. */ protected void initInputStream() throws JooneRuntimeException { if ((URL != null) && (URL != "")) { try { cURL = new URL(URL); InputStream is = cURL.openStream(); StreamInputTokenizer sit; if (getMaxBufSize() > 0) sit = new StreamInputTokenizer(new InputStreamReader(is), getMaxBufSize()); else sit = new StreamInputTokenizer(new InputStreamReader(is)); super.setTokens(sit); } catch (IOException ioe) { log.warn("Could not extract data from the URL '"+URL+"' Message is : " + ioe.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Could not extract data from the URL '"+URL+"' Message is : "+ioe.getMessage()); } } } }
Java
package org.joone.io; import java.beans.*; public class ImageOutputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor//GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( org.joone.io.ImageOutputSynapse.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers//GEN-FIRST:Properties private static final int PROPERTY_buffered = 0; private static final int PROPERTY_colourMode = 1; private static final int PROPERTY_enabled = 2; private static final int PROPERTY_height = 3; private static final int PROPERTY_imageFileType = 4; private static final int PROPERTY_monitor = 5; private static final int PROPERTY_name = 6; private static final int PROPERTY_outputDirectory = 7; private static final int PROPERTY_width = 8; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[9]; try { properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", org.joone.io.ImageOutputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_colourMode] = new PropertyDescriptor ( "colourMode", org.joone.io.ImageOutputSynapse.class, "getColourMode", "setColourMode" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", org.joone.io.ImageOutputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_height] = new PropertyDescriptor ( "height", org.joone.io.ImageOutputSynapse.class, "getHeight", "setHeight" ); properties[PROPERTY_imageFileType] = new PropertyDescriptor ( "imageFileType", org.joone.io.ImageOutputSynapse.class, "getImageFileType", "setImageFileType" ); properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", org.joone.io.ImageOutputSynapse.class, "getMonitor", "setMonitor" ); properties[PROPERTY_monitor].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", org.joone.io.ImageOutputSynapse.class, "getName", "setName" ); properties[PROPERTY_outputDirectory] = new PropertyDescriptor ( "outputDirectory", org.joone.io.ImageOutputSynapse.class, "getOutputDirectory", "setOutputDirectory" ); properties[PROPERTY_width] = new PropertyDescriptor ( "width", org.joone.io.ImageOutputSynapse.class, "getWidth", "setWidth" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers//GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package org.joone.io; import java.util.*; import java.io.*; import org.joone.log.*; import org.joone.engine.*; import org.joone.util.*; import org.joone.net.NetCheck; import org.joone.inspection.Inspectable; import org.joone.inspection.implementations.InputsInspection; import org.joone.exception.JooneRuntimeException; public abstract class StreamInputSynapse extends Synapse implements InputSynapse, Inspectable { /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(StreamInputSynapse.class); //protected Vector column; //private boolean[] colList; private int firstRow = 1; private int lastRow = 0; private int firstCol = 0; private int lastCol = 0; private String advColumnsSel = ""; /** Flag indicating if the stream buffers the data of not. */ private boolean buffered = true; private char decimalPoint = '.'; private boolean StepCounter = true; protected transient int[] cols; protected transient Vector InputVector; protected transient int currentRow = 0; protected transient PatternTokenizer tokens; protected transient boolean EOF = false; private ConverterPlugIn plugIn; private int maxBufSize = 0; private static final long serialVersionUID = -3316265583083866079L; private transient int startFrom = 0; /** List of plug-in listeners (often input connectors). */ List plugInListeners = new ArrayList(); public StreamInputSynapse() { super(); } protected void backward(double[] pattern) { // Not used. } protected void forward(double[] pattern) { outs = pattern; } public synchronized Pattern fwdGet() { if (!isEnabled()) return null; if ((EOF) || (outs == null)) { try { if ( (EOF) && (getMonitor() != null )) { if (isStepCounter()) getMonitor().resetCycle(); } gotoFirstLine(); outs = new double[1]; // Remember that it already has been here } catch (Exception ioe) { log.error("Exception while executing the \"fwdGet\". Message is : " + ioe.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Exception while executing the \"fwdGet\" method. Message is : " + ioe.getMessage()); return zeroPattern(); } } if (currentRow - firstRow > (getMonitor().getNumOfPatterns() - 1)) { try { gotoFirstLine(); } catch (Exception ioe) { log.error("Exception while executing the \"fwdGet\". Message is : " + ioe.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),"Exception while attempting to access the first line. Message is : " + ioe.getMessage()); return zeroPattern(); } } if (isStepCounter()) { // Checks if the next step can be elaborated boolean cont = getMonitor().nextStep(); if (!cont) { /* If not, then creates and returns a zero pattern, * a pattern having count = -1 * this does mean that the net must stop */ reset(); return zeroPattern(); } } // Reads the next input pattern if (isBuffered()) { int actualRow = currentRow - firstRow + (startFrom==0 ? 0 : startFrom-1); if (getInputVector().size() == 0) readAll(); else { if ((currentRow == firstRow) && (getPlugIn() != null) && !skipNewCycle) { getPlugIn().setInputVector(getInputVector()); if (getPlugIn().newCycle()) { fireDataChanged(); } } } if (actualRow < InputVector.size()) { m_pattern = (Pattern) InputVector.elementAt(actualRow); } // Checks if EOF if ((lastRow > 0) && (currentRow >= lastRow)) EOF = true; if ((actualRow + 1) >= InputVector.size()) EOF = true; ++currentRow; } else { try { m_pattern = getStream(); } catch (Exception ioe) { String error = "Exception in "+getName()+". Message is : "; log.error(error + ioe.getMessage()); ioe.printStackTrace(); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),error + ioe.getMessage()); return zeroPattern(); } } m_pattern.setCount(currentRow - firstRow); return m_pattern; } /** * Returns the decimal point accepted * (19/04/00 0.23.56) * @return char */ public char getDecimalPoint() { return decimalPoint; } /** * @return int */ public int getFirstRow() { return firstRow; } /** * @return java.util.Vector */ protected java.util.Vector getInputVector() { if (InputVector == null) InputVector = new Vector(); return InputVector; } /** * @return int */ public int getLastRow() { return lastRow; } protected Pattern getStream() throws java.io.IOException { int x = 0; EOF = (!tokens.nextLine()); if (!EOF) { if (cols == null) { setColList(); } if (cols == null) { return null; // In this case we cannot continue } // even though the output dimension might differ, we create a input pattern // of the size equaling the number of input columns. Plug-ins might adjust // the dimension and otherwise the layer will adjust its dimenstion. This is // beter than creating an input pattern of a size equal to the output dimenstion // in case the number of columns is smaller and fill the pattern with 0, for // the columns where no imput data is available for. inps = new double[cols.length]; for (x = 0; x < cols.length; ++x) inps[x] = tokens.getTokenAt(cols[x] - 1); // Calculates the new current line // and check the EOF ++currentRow; if ((lastRow > 0) && (currentRow > lastRow)) EOF = true; forward(inps); m_pattern = new Pattern(outs); m_pattern.setCount(currentRow - firstRow); return m_pattern; } else return null; } public void gotoFirstLine() throws java.io.IOException { this.gotoLine(firstRow); } /** * Point to the indicated line into the input stream */ public void gotoLine(int numLine) throws java.io.IOException { EOF = false; if (!isBuffered() || (getInputVector().size() == 0)) { PatternTokenizer tk = getTokens(); if (tk != null) { if (isBuffered()) tk.resetInput(); else // patched by Razvan Surdulescu initInputStream(); EOF = false; currentRow = 1; while ((currentRow < numLine) && (!EOF)) { if (tokens.nextLine()) ++currentRow; else EOF = true; } } } currentRow = numLine; if ((lastRow > 0) && (currentRow >= lastRow)) EOF = true; else EOF = false; } /** * Checks if the input synapse is buffered or not * * @return <code>true</code> in case the input stream is buffered, false otherwise. */ public boolean isBuffered() { return buffered; } /** * Returns if reached the EOF * (10/04/00 23.16.20) * @return boolean */ public boolean isEOF() { return EOF; } /** * Returns if this input layer is an active counter of the steps. * Warning: in a neural net there can be only one StepCounter element! * (10/04/00 23.23.26) * @return boolean */ public boolean isStepCounter() { if (getMonitor() != null) if (getMonitor().isSingleThreadMode()) return false; return StepCounter; } public int numColumns() { if (cols == null) setColList(); if (cols == null) return 0; else return cols.length; } // Read all input values and fullfills the buffer public void readAll() { Pattern ptn; getInputVector().removeAllElements(); try { gotoFirstLine(); ptn = getStream(); while (ptn != null) { InputVector.addElement(ptn); if (EOF) break; ptn = getStream(); } if (plugIn != null) { plugIn.setInputVector(InputVector); plugIn.convertPatterns(); } gotoFirstLine(); } catch (java.io.IOException ioe) { String error = "IOException in "+getName()+". Message is : "; log.warn(error + ioe.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),error + ioe.getMessage()); } catch (NumberFormatException nfe) { String error = "IOException in "+getName()+". Message is : "; log.warn(error + nfe.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),error + nfe.getMessage()); } } public synchronized void revPut(Pattern array) { // Not used. } /** * setArrays method. */ protected void setArrays(int rows, int cols) { } /** * Sets the buffer-mode for this input synapse. * * @param aNewBuffered <code>true</code> if the input should be buffered. * <code>false</code> if the input should not be buffered, the input will be * retrieved from the input source every cycle again. * <p><b>Whenever any converter plug in is added, the buffer-mode will be set * to <code>true</code>, regardless of the parameter's argument. </b></p> */ public void setBuffered(boolean aNewBuffered) { if(plugIn == null) { buffered = aNewBuffered; } else { // If a plugin exists, the input synapse must be buffered // to permit to the plugin to work correctly. buffered = true; } } /** * Sets the list of columns that must be returned as the pattern * Creation date: (18/10/2000 0.45.52) * @param cols java.util.Vector */ protected void setColList() { int i; if (getAdvancedColumnSelector().trim().length() > 0) { CSVParser parser = new CSVParser(getAdvancedColumnSelector().trim()); try { cols = parser.parseInt(); } catch (NumberFormatException nfe) { new NetErrorManager(getMonitor(), nfe.getMessage()); } } else { if ((getFirstCol() == 0) || (getLastCol() == 0)) return; cols = new int[getLastCol() - getFirstCol() + 1]; for (i=getFirstCol(); i <= getLastCol(); ++i) cols[i - getFirstCol()] = i; } } public void setDecimalPoint(char dp) { decimalPoint = dp; if (tokens != null) tokens.setDecimalPoint(dp); } protected void setDimensions(int rows, int cols) { } protected void setEOF(boolean newEOF) { EOF = newEOF; } /** * Inserire qui la descrizione del metodo. * Data di creazione: (11/04/00 1.22.28) * @param newFirstRow int */ public void setFirstRow(int newFirstRow) { myFirstRow = firstRow; if (firstRow != newFirstRow) { firstRow = newFirstRow; this.resetInput(); } } /** * Reset the input stream to read its content again */ public synchronized void resetInput() { restart(); tokens = null; notifyAll(); } private void restart() { getInputVector().removeAllElements(); EOF = false; cols = null; } /** * Inserire qui la descrizione del metodo. * Data di creazione: (11/04/00 1.22.34) * @param newLastRow int * */ public void setLastRow(int newLastRow) { myLastRow = lastRow; if (lastRow != newLastRow) { lastRow = newLastRow; this.resetInput(); } } /** * Adds a plug in to the stream input synapse for data preprocessing. If one * or more plug ins are already added to the this synapse, the plug in will * be added at the end of the list of plug ins. * * @param aNewPlugIn The new converter plug in to add (at the end of the list). * @return <code>true</code> when the plug in is added, <code>false</code> when * the plug in is not added, e.g. in case the plug in is already added / * connected to another synapse. */ public boolean addPlugIn(ConverterPlugIn aNewPlugIn) { if(plugIn == aNewPlugIn) { return false; } // The null parameter is used to detach or delete a plugin if(aNewPlugIn == null) { // We need to declare the next plugin, if existing, // as not more used, so it could be used again. if (plugIn != null) { plugIn.setConnected(false); } plugIn = null; resetInput(); return true; } if(aNewPlugIn.isConnected()) { // The new plugin is already connected to another plugin, // hence cannot be used. return false; } if(plugIn == null) { aNewPlugIn.setConnected(true); aNewPlugIn.addPlugInListener(this); setBuffered(true); plugIn = aNewPlugIn; resetInput(); return true; } else { return plugIn.addPlugIn(aNewPlugIn); } } /** * Removes (and disconnects) all (cascading) plug-ins. */ public void removeAllPlugIns() { if(plugIn != null) { plugIn.setConnected(false); plugIn.removeAllPlugIns(); plugIn = null; } } /** * Sets the plugin for the data preprocessing. * @param newPlugIn the plug in to set * * @deprecated {@link #addPlugIn(ConverterPlugIn)}. If you want to replace * the plug in by setting a new plug in please use * {@link #removeAllPlugIns(ConverterPlugIn)} and {@link #addPlugIn(ConverterPlugIn)}. */ public boolean setPlugin(ConverterPlugIn newPlugIn) { if (newPlugIn == plugIn) return false; if (newPlugIn == null) plugIn.setConnected(false); else { if (newPlugIn.isConnected()) return false; newPlugIn.setConnected(true); newPlugIn.addPlugInListener(this); buffered = true; } plugIn = newPlugIn; this.resetInput(); return true; } /** Gets the attached ConverterPlugin, if any * @return neural.engine.ConverterPlugIn */ public ConverterPlugIn getPlugIn() { return plugIn; } /** Added for XML serialization * **** DO NOT USE **** * Use getPlugin instead */ public void setPlugIn(ConverterPlugIn newPlugIn) { this.setPlugin(newPlugIn); } /** * Inserire qui la descrizione del metodo. * Data di creazione: (10/04/00 23.23.26) * @param newStepCounter boolean */ public void setStepCounter(boolean newStepCounter) { StepCounter = newStepCounter; } protected void writeObjectBase(ObjectOutputStream out) throws IOException { int s = 0; if (isBuffered()) { s = getInputVector().size(); if ((s == 0) && (tokens != null)) { gotoFirstLine(); readAll(); } } if (out.getClass().getName().indexOf("xstream") != -1) { out.defaultWriteObject(); if (isBuffered()) { out.writeObject(InputVector); } } else { out.defaultWriteObject(); if (isBuffered()) { s = getInputVector().size(); out.writeInt(s); for (int i = 0; i < s; ++i) { out.writeObject(InputVector.elementAt(i)); } } } } protected void readObjectBase(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (in.getClass().getName().indexOf("xstream") != -1) { if (isBuffered()) { InputVector = (Vector)in.readObject(); } } else { if (isBuffered()) { Pattern ptn; getInputVector().removeAllElements(); int s = in.readInt(); for (int i = 0; i < s; ++i) { ptn = (Pattern) in.readObject(); InputVector.addElement(ptn); } } } if (advColumnsSel == null) { advColumnsSel = ""; } if (plugInListeners == null) { plugInListeners = new ArrayList(); } } /** Getter for property lastCol. * @return Value of property lastCol. * @deprecated */ public int getLastCol() { return lastCol; } /** Setter for property lastCol. * @param lastCol New value of property lastCol. * @deprecated */ public void setLastCol(int lastCol) throws IllegalArgumentException { if (this.lastCol != lastCol) { this.lastCol = lastCol; cols = null; } } /** Getter for property firstCol. * @return Value of property firstCol. * @deprecated */ public int getFirstCol() { return firstCol; } /** Setter for property firstCol. * @param firstCol New value of property firstCol. * @deprecated */ public void setFirstCol(int firstCol) throws IllegalArgumentException { if (this.firstCol != firstCol) { this.firstCol = firstCol; cols = null; } } public String getAdvancedColumnSelector() { return advColumnsSel; } public void setAdvancedColumnSelector(String newAdvColSel) { if (advColumnsSel.compareTo(newAdvColSel) != 0) { advColumnsSel = newAdvColSel; this.resetInput(); } } public void dataChanged(PlugInEvent data) { resetInput(); } /** Getter for property tokens. * @return Value of property tokens. */ protected PatternTokenizer getTokens() throws JooneRuntimeException { if (tokens == null) initInputStream(); return tokens; } protected void setTokens(PatternTokenizer tkn) { tokens = tkn; if (tokens != null) tokens.setDecimalPoint(this.getDecimalPoint()); restart(); } protected Pattern zeroPattern() { Pattern pat = new Pattern(new double[getOutputDimension()]); pat.setCount(-1); return pat; } // You must override this method and insert here the setting of the object tokens. protected abstract void initInputStream() throws JooneRuntimeException; /** * Check that parameters are set correctly. * * @see Synapse * @return validation errors. */ public TreeSet check() { // Get the parent's cehck messages. TreeSet checks = super.check(); // Check that the first row is greater than 0. if (firstRow <= 0) { checks.add(new NetCheck(NetCheck.FATAL, "First Row parameter cannot be less than 1.", this)); } if ( advColumnsSel == null ) if ((firstCol <= 0 || lastCol <= 0)) { checks.add(new NetCheck(NetCheck.FATAL, "Input columns not set.", this)); } else // if ( advColumnsSel != null ) { if ( advColumnsSel.trim().length() == 0 ) checks.add(new NetCheck(NetCheck.FATAL, "Input columns not set.", this)); else { // Check if it can be parsed here... } // } if (isBuffered()) { if (getInputVector().size() == 0) try { getTokens(); } catch (JooneRuntimeException jre) { checks.add(new NetCheck(NetCheck.FATAL, "Cannot initialize the input stream: "+jre.getMessage(), this)); } } if ( getPlugIn() != null ) { getPlugIn().check(checks); // Should propogate down the plugins } return checks; } public Collection Inspections() { Collection col = new ArrayList(); if (isBuffered()) { if (getInputVector().size() == 0) if (getTokens() != null) readAll(); col.add(new InputsInspection(getInputVector())); } else { col.add(new InputsInspection(null)); } return col; } public String InspectableTitle() { return getName(); } /** reset the state of the input synapse * */ public void reset() { super.reset(); outs = null; // This will force the call to gotoFirstLine when fwdGet is called } /** Getter for property maxBufSize. * @return Value of property maxBufSize. * */ public int getMaxBufSize() { return maxBufSize; } /** Setter for property maxBufSize. * @param maxBufSize New value of property maxBufSize. * */ public void setMaxBufSize(int maxBufSize) { this.maxBufSize = maxBufSize; } /** * Getter for property inputPatterns. * Added for XML serialization * @return Value of property inputPatterns. */ public Vector getInputPatterns() { return InputVector; } /** * Setter for property inputPatterns. * Added for XML serialization * @param inputPatterns New value of property inputPatterns. */ public void setInputPatterns(Vector inputPatterns) { this.InputVector = inputPatterns; } /* ************************************************************** * Starting from here there is all the code added in order to * implement the new I/O framework (see the InputConnector class) * by P. Marrone (13/09/2004) */ private int myFirstRow = 1; private int myLastRow = 0; // Used to indicate if the plugin.newCycle method must be invoked private transient boolean skipNewCycle = false; /** This method is called by the InputConnector in order * to get the next input pattern available for that connector */ public synchronized Pattern fwdGet(InputConnector conn) { if (isBuffered() && (getInputVector().size() == 0)) { // It'll enter here only the first time, to fill the internal buffer firstRow = myFirstRow; lastRow = myLastRow; startFrom = 0; skipNewCycle = false; readAll(); } // Context switching if (conn == null) return null; // as only one InputConnector can have stepCounter=true, // the plugin.newCycle is called only once skipNewCycle = !conn.isStepCounter(); firstRow = conn.getFirstRow(); lastRow = conn.getLastRow(); EOF = conn.isEOF(); currentRow = conn.getCurrentRow(); startFrom = firstRow; Pattern retValue = fwdGet(); // Reset the context firstRow = myFirstRow; lastRow = myLastRow; startFrom = 0; return retValue; } /** * Getter for property currentRow. * @return Value of property currentRow. */ public int getCurrentRow() { return currentRow; } /** * Adds a plug-in lsitener to this input stream. * * @param aListener the listener to add */ public void addPlugInListener(PlugInListener aListener) { if(!plugInListeners.contains(aListener)) { plugInListeners.add(aListener); } } /** * Removes a plug-in listener from this input stream. * * @param aListener the listener to remove */ public void removePlugInListener(PlugInListener aListener) { plugInListeners.remove(aListener); } /** * Gets all the plug-in listeners. * * @return the plug-in listeners. */ public List getAllPlugInListeners() { return plugInListeners; } /** * Fires an event to the plug-in listeners notifying that the underlying data * has changed. */ protected void fireDataChanged() { Object[] myList; synchronized (this) { myList = getAllPlugInListeners().toArray(); } for (int i=0; i < myList.length; ++i) { if (myList[i] != null) { ((PlugInListener)myList[i]).dataChanged(new PlugInEvent(this)); } } } }
Java
package org.joone.io; import java.util.*; import java.io.*; import java.awt.image.PixelGrabber; import java.awt.Image; import java.net.URL; import javax.imageio.ImageIO; import org.joone.log.*; /** * This tokenizer is responsible for collecting data from a list of Image file names or Image objects and feeding the data * from the Images into a tokenized array of values for feeding into the Neural network. * GIF, JPG and PNG image file formats can be read. The tokenizer operates in two modes, colour and grey scale. * <P> * <B>Colour Mode</B> * In colour mode the tokenizer produces seperate RGB input values in the range 0 to 1 from the * image. So using an image of width 10 and height 10 there will be 10x10x3 inputs in the range 0 to 1. * The individual colour components are calculated by obtaining the RGB values from the image. These value * are initially in an ARGB format. Transparency is removed and the RGB value extracted and normalised * between 0 and 1. * </P> * <P> * <B>Non Colour Mode / Grey Scale Mode </B> * In this mode the tokenizer treats each input value as a grey scale value for each pixel. In this mode * only Width*Height values are required. To produce the final image the Red, Green and Blue components * are the set to this same value. * The grey scale component is calculated by obtaining the RGB values from the image. These value * are initially in an ARGB format. Transparency is removed and the RGB value extracted, averaged and normalised * to produce one grey scale value between 0 and 1. * </P> * @author Julien Norman */ public class ImageInputTokenizer implements PatternTokenizer { // Required Image Width and Height private int RequiredWidth = 0, RequiredHeight = 0; private int TotalTokens = 0; private double [] ImageTokens = null; // Holds a Vector or URL's to the required Image private Vector ImageFileList = new Vector(); // An Array of Images provided by user code. private Image [] ArrayOfInputImages = null; private int TotalInputImages = 0; // Indicates if Images come from a list of files, false implies Array of Images. private boolean FileMode = true; // Indicates if 3 tokens (r,g,b) for each pixel, else one grey scale token private boolean ColourMode = true; private int CurrentImageNo = 0; private int CurrentToken = 0; private int MarkedImage = 0; private int MarkedToken = 0; /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(ImageInputTokenizer.class); /** Creates new ImageInputTokenizer * @param in */ public ImageInputTokenizer(int req_width,int req_height,Vector file_list,boolean colour) throws java.io.IOException { FileMode = true; RequiredWidth = req_width; RequiredHeight = req_height; ColourMode = colour; if ( ColourMode ) TotalTokens = RequiredWidth*RequiredHeight*3; else TotalTokens = RequiredWidth*RequiredHeight; ImageFileList = file_list; if ( ImageFileList != null) TotalInputImages = ImageFileList.size(); else TotalInputImages = -1; ImageTokens = new double[TotalTokens]; } /** Creates new ImageInputTokenizer * @param in */ public ImageInputTokenizer(int req_width,int req_height,Image [] the_images,boolean colour) throws java.io.IOException { FileMode = false; RequiredWidth = req_width; RequiredHeight = req_height; ColourMode = colour; if ( ColourMode ) TotalTokens = RequiredWidth*RequiredHeight*3; else TotalTokens = RequiredWidth*RequiredHeight; ArrayOfInputImages = the_images; if ( the_images != null) TotalInputImages = the_images.length; else TotalInputImages = -1; ImageTokens = new double[TotalTokens]; } /** Return the current line number. * @return the current line number */ public int getLineno() { return CurrentImageNo; } /** * Gets the number of tokens on the current line. */ public int getNumTokens() throws java.io.IOException { return TotalTokens; } /** * Gets the token (RGB normalised between 0 and 1) at the specified position. * @return double The token (combined RGB) at the specified position on the current line. * @param posiz An int index into the current lines tokens. */ public double getTokenAt(int posiz) throws java.io.IOException { if ( posiz < TotalTokens ) if ( ImageTokens != null) return (ImageTokens[posiz]); else return(0); else return(0); } /** * Insert the method's description here. * Creation date: (17/10/2000 0.13.45) * @return float[] */ public double[] getTokensArray() { return(ImageTokens); } /** * Mark the current position. */ public void mark() throws java.io.IOException { MarkedImage = CurrentImageNo; MarkedToken = CurrentToken; } /** Fetchs the next line and extracts all the tokens * @return false if EOF, otherwise true * @throws IOException if an I/O Error occurs */ public boolean nextLine() throws java.io.IOException { boolean result = false; if ((CurrentImageNo >= TotalInputImages) || (TotalInputImages <= 0)) return false; else { if ( FileMode ) // Load the next Image from the file list. { try { // Try to get the Image URL theFile = (URL)ImageFileList.get(CurrentImageNo); Image tImg = ImageIO.read(theFile); result = processImage(tImg); } catch(Exception ex) { log.error("Caught Error processing Image : "+ex.toString()); } } else // Get the Image from the passed in array of images. { if ( (ArrayOfInputImages != null) && (ArrayOfInputImages.length >= 1)) { result = processImage(ArrayOfInputImages[CurrentImageNo]); } } CurrentImageNo++; return(result); } } /** Return the next token's double value in the current line * @return the next double value */ private double nextToken() throws java.io.IOException { return this.nextToken(null); } /** Return the next token's double value in the current line; * tokens are separated by the characters contained in delim * @return the next double value * @param delim String containing the delimitators characters */ private double nextToken(String delim) throws java.io.IOException { if ( CurrentToken < TotalTokens) { double value = ImageTokens[CurrentToken]; CurrentToken++; return(value); } else return 0; } /** Go to the last marked position. Begin of input stream if no mark detected. */ public void resetInput() throws java.io.IOException { if ( (MarkedImage > 0) || (MarkedToken > 0)) { CurrentImageNo = MarkedImage; CurrentToken = MarkedToken; } else { // Goto start of Images again. CurrentImageNo = 0; } if ( FileMode ) // Load the right Image from the file list. { try { URL theFile = (URL)ImageFileList.get(CurrentImageNo); Image tImg = ImageIO.read(theFile.openStream()); processImage(tImg); } catch(Exception ex) { log.error("Error processing/loading image : "+ex.toString()); } } else // Get the Image from the passed in array of images. { if ( (ArrayOfInputImages != null) && (ArrayOfInputImages.length >= 1)) { processImage(ArrayOfInputImages[CurrentImageNo]); } } } public void setDecimalPoint(char dp) { return; } public char getDecimalPoint() { return('.'); } /** * Processes and returns the final image after scaling etc for input to network. */ private boolean processImage(Image theImage) { double Red = 0,Green = 0, Blue = 0; double Grey = 0; int [] TempTokens = null; try { if ( ColourMode ) TempTokens = new int[TotalTokens/3]; else TempTokens = new int[TotalTokens]; Image TempImage = theImage.getScaledInstance(RequiredWidth,RequiredHeight,Image.SCALE_AREA_AVERAGING); PixelGrabber pixgrab = new java.awt.image.PixelGrabber(TempImage,0,0,TempImage.getWidth(null),TempImage.getHeight(null),TempTokens,0,TempImage.getWidth(null)); if ( pixgrab.grabPixels() == true) { // Ok should have sRGB data in TempTokens array, now need to convert the data // to normalised values between 0 and 1 for presentation to network. // Now loop through TempTokens array and convert //double div = 0x00FFFFFF; if ( ColourMode ) { for ( int i=0;i<TempTokens.length;i++) { Red = ((double)((TempTokens[i]&0x00FF0000)>>16))/255.0; Green = ((double)((TempTokens[i]&0x0000FF00)>>8))/255.0; Blue = ((double)((TempTokens[i]&0x000000FF)))/255.0; ImageTokens[(i*3)] = Red; ImageTokens[(i*3)+1] = Green; ImageTokens[(i*3)+2] = Blue; //System.out.format("In RGB = %x",TempTokens[i]); } } else // Grey Scale { for ( int i=0;i<TempTokens.length;i++) { Red = ((double)((TempTokens[i]&0x00FF0000)>>16))/255.0; Green = ((double)((TempTokens[i]&0x0000FF00)>>8))/255.0; Blue = ((double)((TempTokens[i]&0x000000FF)))/255.0; Grey = (Red + Blue + Green)/3; ImageTokens[i] = Grey; } } } else { log.error("Failed to grab image pixels due to error."); return(false); } } catch(Exception ex) { log.error("Error processing image : "+ex.toString()); return(false); } return(true); } }
Java
package org.joone.io; import java.util.*; import org.joone.engine.*; import org.joone.util.*; import org.joone.log.*; public abstract class StreamOutputSynapse extends Synapse implements PlugInListener { /** * Logger * */ private static final ILogger log = LoggerFactory.getLogger(StreamOutputSynapse.class); private char separator = ';'; private static final long serialVersionUID = 7344684413113722785L; // The FIFO used for buffering protected transient Fifo fifo; // Are we buffering the output. Can be used for OutputConverters that need all data in order to convert or if a buffer is required. // Buffer = true means store all the data then write in one go. private boolean buffered = true; // If we are using buffered mode then this will hold the buffered patterns. private transient Vector buffered_patterns; // Support for Output Conversion protected OutputConverterPlugIn nextPlugIn = null; public StreamOutputSynapse() { super(); } protected void backward(double[] pattern) { // Non usato. } protected void forward(double[] pattern) { outs = pattern; } /** * The standard fwdPut method. This method performs buffering of pattern data if required according to the buffered flag. * If buffered mode is set then the default multiple writing method write(Pattern [] patterns) method is called to loop through all * the patterns calling the single pattern writing abstract method write(Pattern pattern) to write the pattern to the appropriate media. * If the synapse is not in buffered mode then the pattern is simply passed to the single pattern writing abstract * method write(Pattern pattern) to write the pattern to the appropriate media. * * Custom xxxOutputSynapse classes can over ride this method if they would like to perform a custom buffering implementation. * In this case it will be the responsiblity of the custom class to ensure all patterns are output correctly and any conversion is done * prior to writing data. */ public synchronized void fwdPut(Pattern pattern) { if (isEnabled()) { // Check that this synapse is enabled or not try { if ( isBuffered() ) // Check if it's using buffered mode or not { if ( pattern.getCount() > -1) // If we still going through patterns then simply add them to the fifo { // Push Pattern onto buffered FIFO. m_pattern = pattern; inps = (double[]) pattern.getArray(); forward(inps); m_pattern.setArray(outs); getFifo().push(m_pattern.clone()); items = fifo.size(); } else // Otherwise we have finished so convert all patterns { // We've come to the end so write do any buffer conversion (if applicable) and output the data // Some xxxOutputSynapse might need to know they are on the last pattern so also add the count=-1 pattern. //m_pattern = pattern; //inps = (double[]) pattern.getArray(); //forward(inps); //m_pattern.setArray(outs); // Don't foward if on a stop pattern getFifo().push(pattern.clone()); items = fifo.size(); int num_patterns = fifo.size(); buffered_patterns = new Vector(); for ( int i = 0; i<num_patterns;i++) { buffered_patterns.addElement(((Pattern)fifo.pop()).clone()); } // Conversion i.e unnormalizer would have to be done here. ConverterPlugin.convert(buffered_patterns); // NOTE : Any Raw Data conversion i.e TextConverter will have to be called by the converting xxxOutputSynapse. if ( nextPlugIn != null ){ nextPlugIn.setInputVector(buffered_patterns); nextPlugIn.convertPatterns(); } write(buffered_patterns); } } else // We are not in buffered mode so write the single pattern out { // We are not in buffered mode so just write the pattern // Also need to do any non-buffered (if applicable) conversion here // Conversion i.e unnormalizer would have to be done here. E.g ConverterPlugin.convert(pattern); // NOTE : Any Raw Data conversion i.e TextConverter will have to be called by the converting xxxOutputSynapse. // NOTE : Also the RawConverter has not yet been decided at the moment. if ( pattern.getCount() > -1) // Only foward and convert if not on a stop pattern { inps = (double[]) pattern.getArray(); forward(inps); items=1; if ( nextPlugIn != null ){ nextPlugIn.setPattern(pattern); nextPlugIn.convertPattern(); } } write(pattern); // Write the pattern } // End else not buffered } catch (NumberFormatException nfe) { String error = "NumberFormatException in "+getName()+". Message is : "; log.warn(error + nfe.getMessage()); if ( getMonitor() != null ) new NetErrorManager(getMonitor(),error + nfe.getMessage()); } } // End of if enabled notifyAll(); } // End fwdPut method. /** * This function writes all of the buffered patterns to the appropriate media. If required this function can be over written to allow * custom output synapses greater control of the pattern writing. This method is only used if the StreamOutputSynapse is buffered. */ private void write(Vector patterns) { if ( patterns != null ) { for ( int i=0;i<patterns.size();i++) // Loop through and write pattern write((Pattern)patterns.elementAt(i)); } } /** * Custom xxxOutputSynapses need to implement at least this method. The custom synapse should write the pattern out to the * appropriate media. All patterns including the ending pattern with pattern.getCount()=-1 will be passed to this method so that * custom output synapses can perform final processing. */ public abstract void write(Pattern pattern); /** * Returns the column separator * creation date: (23/04/00 0.50.18) * @return char */ public char getSeparator() { return separator; } public synchronized Pattern revGet() { // Non usato. return null; } /** * setArrays method comment. */ protected void setArrays(int rows, int cols) {} /** * Dimensiona l'elemento * @param int rows - righe * @param int cols - colonne */ protected void setDimensions(int rows, int cols) {} /** * Inserire qui la descrizione del metodo. * Data di creazione: (23/04/00 0.50.18) * @param newSeparator char */ public void setSeparator(char newSeparator) { separator = newSeparator; } /** * Sets the buffered status of this synapse. */ public void setBuffered(boolean buf) { buffered = buf; } /** * Checks the buffered status of this synapse. */ public boolean isBuffered() { return(buffered); } public TreeSet check() { TreeSet checks = super.check(); //checks.add(new NetCheck(NetCheck.ERROR, "File Name not set." , this)); // Call all OutputConverterPlugins here if ( nextPlugIn != null ) { nextPlugIn.check(checks); // Should propogate down the plugins } return checks; } /** Getter for property fifo. * @return Value of property fifo. * */ protected Fifo getFifo() { if (fifo == null) fifo = new Fifo(); return fifo; } /** * @return neural.engine.ConverterPlugIn */ public OutputConverterPlugIn getPlugIn() { return nextPlugIn; } /** * Sets the plugin for the data postprocessing * @param newPlugIn neural.engine.OutputConverterPlugIn * * @deprecated use {@link #addPlugIn(OutputConverterPlugIn)} */ public boolean setPlugIn(OutputConverterPlugIn newPlugIn) { if (newPlugIn == nextPlugIn) return false; if (newPlugIn == null) nextPlugIn.setConnected(false); else { if (newPlugIn.isConnected()) return false; newPlugIn.setConnected(true); newPlugIn.addPlugInListener(this); buffered = true; } nextPlugIn = newPlugIn; getFifo().removeAllElements(); return true; } /** * Adds a plug in to the stream output synapse for data preprocessing. If one * or more plug ins are already added to the this synapse, the plug in will * be added at the end of the list of plug ins. * * @param aNewPlugIn The new converter plug in to add (at the end of the list). * @return <code>true</code> when the plug in is added, <code>false</code> when * the plug in is not added, e.g. in case the plug in is already added / * connected to another synapse. */ public boolean addPlugIn(OutputConverterPlugIn aNewPlugIn) { if(nextPlugIn == aNewPlugIn) { return false; } // The null parameter is used to detach or delete a plugin if(aNewPlugIn == null) { // We need to declare the next plugin, if existing, // as not more used, so it could be used again. if (nextPlugIn != null) { nextPlugIn.setConnected(false); } nextPlugIn = null; getFifo().removeAllElements(); return true; } if(aNewPlugIn.isConnected()) { // The new plugin is already connected to another plugin, // hence cannot be used. return false; } if(nextPlugIn == null) { aNewPlugIn.setConnected(true); aNewPlugIn.addPlugInListener(this); setBuffered(true); nextPlugIn = aNewPlugIn; getFifo().removeAllElements(); return true; } else { return nextPlugIn.addPlugIn(aNewPlugIn); } } /** * Removes (and disconnects) all (cascading) plug-ins. */ public void removeAllPlugIns() { if(nextPlugIn != null) { nextPlugIn.setConnected(false); nextPlugIn.removeAllPlugIns(); nextPlugIn = null; } } public void dataChanged(PlugInEvent data) { getFifo().removeAllElements(); } }
Java
package org.joone.io; /** Interface to extract tokens from an input stream */ public interface PatternTokenizer { /*** Return the current line number. * @return the current line number */ public int getLineno(); public int getNumTokens() throws java.io.IOException; /** * Returns the value of the token at 'posiz' column of the current line * Creation date: (17/10/2000 0.30.08) * @return float * @param posiz int */ public double getTokenAt(int posiz) throws java.io.IOException; /** * Returns an array of values of the current line * Creation date: (17/10/2000 0.13.45) * @return float[] */ public double[] getTokensArray(); /** marks the current position. * @throws IOException if an I/O Error occurs */ public void mark() throws java.io.IOException; /** Go to the next line * @return false if EOF, otherwise true * @throws IOException if an I/O Error occurs */ public boolean nextLine() throws java.io.IOException; /** Go to the last marked position. Begin of input stream if no mark detected. */ public void resetInput() throws java.io.IOException; public char getDecimalPoint(); public void setDecimalPoint(char decimalPoint); }
Java
package org.joone.io; import java.util.*; import java.io.*; import org.joone.util.*; import org.joone.engine.Monitor; import org.joone.engine.Pattern; /** This class acts as a switch that can connect its output to one of its connected * input synapses. * Many input synapses can be attached to the switch calling the method addInputSynapse, * but only one is attached to the output; which one is comnnected is determined * by the call to the method setActiveInput, passing to it the name of * the selected synapse. */ public class InputSwitchSynapse extends StreamInputSynapse implements Serializable { protected Vector inputs; private StreamInputSynapse activeSynapse; private StreamInputSynapse defaultSynapse; private String name; private Monitor mon; private int outputDimension; private static final long serialVersionUID = 9025876263540714672L; /** The constructor */ public InputSwitchSynapse() { initSwitch(); mon = null; outputDimension = 0; } protected void initSwitch() { inputs = new Vector(); activeSynapse = defaultSynapse = null; } public void init() { super.init(); for (int i=0; i < inputs.size(); ++i) { StreamInputSynapse inp = (StreamInputSynapse)inputs.elementAt(i); inp.init(); } } /** Resets the switch, connecting the default synapse to the output */ public void resetSwitch() { setActiveSynapse(getDefaultSynapse()); } public void reset() { for (int i=0; i < inputs.size(); ++i) { StreamInputSynapse inp = (StreamInputSynapse)inputs.elementAt(i); inp.reset(); } } /** Removes an input synapse from the switch * @param inputName The name of the synapse to remove * @return false if the synapse cannot be found */ public boolean removeInputSynapse(String inputName) { boolean retValue = false; StreamInputSynapse sis = getInputSynapse(inputName); if (sis != null) { inputs.removeElement(sis); sis.setInputFull(false); if (inputs.size() > 0) { if (getActiveInput().equalsIgnoreCase(inputName)) setActiveSynapse((StreamInputSynapse)inputs.elementAt(0)); if (getDefaultInput().equalsIgnoreCase(inputName)) setDefaultSynapse((StreamInputSynapse)inputs.elementAt(0)); } else { setActiveInput(""); setDefaultInput(""); } retValue = true; } return retValue; } protected StreamInputSynapse getInputSynapse(String inputName) { StreamInputSynapse inp = null; for (int i=0; i < inputs.size(); ++i) { inp = (StreamInputSynapse)inputs.elementAt(i); if (inp.getName().equalsIgnoreCase(inputName)) { return inp; } } return null; } /** Adds an input synapse to the switch * @param newInput the new input synapse */ public boolean addInputSynapse(StreamInputSynapse newInput) { boolean retValue = false; if (!inputs.contains(newInput)) { if (!newInput.isInputFull()) { inputs.addElement(newInput); newInput.setOutputDimension(outputDimension); newInput.setMonitor(mon); newInput.setStepCounter(super.isStepCounter()); newInput.setInputFull(true); if (inputs.size() == 1) { setDefaultInput(newInput.getName()); setActiveInput(newInput.getName()); } retValue = true; } } return retValue; } /** Returns the name of the actual connected input synapse * @return The name of the connected input synapse */ public String getActiveInput(){ if (activeSynapse != null) return activeSynapse.getName(); else return ""; } /** Sets the input synapse connected to the output * @param newActiveInput the name of the input synapse to connect */ public void setActiveInput(String newActiveInput) { StreamInputSynapse inp = getInputSynapse(newActiveInput); this.activeSynapse = inp; } /** Returns the name of the default input synapse that is connected * when the reset method is called * @return the name of the default synapse */ public String getDefaultInput() { if (defaultSynapse != null) return defaultSynapse.getName(); else return ""; } /** Sets the name of the default input synapse that is connected * when the reset method is called * @param newDefaultInput the name of the default input synapse */ public void setDefaultInput(String newDefaultInput) { StreamInputSynapse inp = getInputSynapse(newDefaultInput); defaultSynapse = inp; } /** Getter for property activeSynapse. * @return Value of property activeSynapse. */ protected StreamInputSynapse getActiveSynapse() { return activeSynapse; } /** Setter for property activeSynapse. * @param activeSynapse New value of property activeSynapse. */ protected void setActiveSynapse(StreamInputSynapse activeSynapse) { this.activeSynapse = activeSynapse; } /** Getter for property defaultSynapse. * @return Value of property defaultSynapse. */ protected StreamInputSynapse getDefaultSynapse() { return defaultSynapse; } /** Setter for property defaultSynapse. * @param defaultSynapse New value of property defaultSynapse. */ protected void setDefaultSynapse(StreamInputSynapse defaultSynapse) { this.defaultSynapse = defaultSynapse; } /** Returns the name of the input synapse * @return <{String}> */ public String getName() { return name; } /** Sets the name of the input synapse * @param name String */ public void setName(String name) { this.name = name; } //------ Methods and parameters mapped on the active input synapse ------- /** Sets the dimension of the input synapse * @param newOutputDimension int */ public void setOutputDimension(int newOutputDimension) { this.outputDimension = newOutputDimension; for (int i=0; i < inputs.size(); ++i) { StreamInputSynapse inp = (StreamInputSynapse)inputs.elementAt(i); inp.setOutputDimension(newOutputDimension); } } /** Method to put an error pattern backward to the previous layer * @param pattern neural.engine.Pattern */ public void revPut(Pattern pattern) { if (activeSynapse != null) activeSynapse.revPut(pattern); } /** Returns the pattern coming from the previous layer during the recall phase * @return neural.engine.Pattern */ public Pattern fwdGet() { if (activeSynapse != null) return activeSynapse.fwdGet(); else return null; } /** Returns the pattern coming from the previous layer during the recall phase. * This method is called by the InputConnector class * @return neural.engine.Pattern */ public Pattern fwdGet(InputConnector conn) { if (activeSynapse != null) return activeSynapse.fwdGet(conn); else return null; } /** Returns the dimension of the input synapse * @return int */ public int getOutputDimension() { return outputDimension; } /** Returns the monitor * @return <{Monitor}> */ public Monitor getMonitor() { return mon; } /** Sets the Monitor object of the input synapse * @param newMonitor org.joone.engine.Monitor */ public void setMonitor(Monitor newMonitor) { this.mon = newMonitor; for (int i=0; i < inputs.size(); ++i) { StreamInputSynapse inp = (StreamInputSynapse)inputs.elementAt(i); inp.setMonitor(newMonitor); } } protected void backward(double[] pattern) { // Not used } protected void forward(double[] pattern) { // Not used } public Vector getAllInputs() { return inputs; } public void setAllInputs(Vector inps) { inputs = inps; if (inputs != null) { for (int i=0; i < inputs.size(); ++i) { StreamInputSynapse inp = (StreamInputSynapse)inputs.elementAt(i); inp.setInputFull(true); } } } public void resetInput() { for (int i=0; i < inputs.size(); ++i) { StreamInputSynapse inp = (StreamInputSynapse)inputs.elementAt(i); inp.resetInput(); } this.reset(); } protected void initInputStream() { // Not used } public void setStepCounter(boolean newStepCounter) { super.setStepCounter(newStepCounter); for (int i=0; i < inputs.size(); ++i) { StreamInputSynapse inp = (StreamInputSynapse)inputs.elementAt(i); inp.setStepCounter(newStepCounter); } } /** * Point to the indicated line into the input stream */ public void gotoLine(int numLine) throws IOException { if (activeSynapse != null) activeSynapse.gotoLine(numLine); } public void dataChanged(PlugInEvent data) { // Not used } public void setDecimalPoint(char dp) { if (activeSynapse != null) activeSynapse.setDecimalPoint(dp); } /** * Returns if reached the EOF * (10/04/00 23.16.20) * @return boolean */ public boolean isEOF() { if (activeSynapse != null) return activeSynapse.isEOF(); else return false; } public void readAll() { if (activeSynapse != null) activeSynapse.readAll(); } /** * @param newBuffered boolean */ public void setBuffered(boolean newBuffered) { if (activeSynapse != null) activeSynapse.setBuffered(newBuffered); } /** * Returns if the input synapse is buffered * (10/04/00 23.11.30) * @return boolean */ public boolean isBuffered() { if (activeSynapse != null) return activeSynapse.isBuffered(); else return false; } /** * @return neural.engine.ConverterPlugIn */ public ConverterPlugIn getPlugIn() { if (activeSynapse != null) return activeSynapse.getPlugIn(); else return null; } /** * Returns if this input layer is an active counter of the steps. * Warning: in a neural net there can be only one StepCounter element! * (10/04/00 23.23.26) * @return boolean */ public boolean isStepCounter() { if (activeSynapse != null) return activeSynapse.isStepCounter(); else return false; } public void gotoFirstLine() throws IOException { if (activeSynapse != null) activeSynapse.gotoFirstLine(); } public void removeAllInputs() { for (int i=0; i < inputs.size(); ++i) { StreamInputSynapse inp = (StreamInputSynapse)inputs.elementAt(i); inp.setInputFull(false); } initSwitch(); } /** * Check that parameters are set correctly. * * @see Synapse * @return validation errors. */ public TreeSet check() { // Get the parent's cehck messages. TreeSet checks = new TreeSet(); StreamInputSynapse inp; for (int i=0; i < inputs.size(); ++i) { inp = (StreamInputSynapse)inputs.elementAt(i); checks.addAll(inp.check()); } return checks; } /** @return int * */ public int getFirstRow() { if (activeSynapse != null) return activeSynapse.getFirstRow(); else return 0; } /** @return int * */ public int getLastRow() { if (activeSynapse != null) return activeSynapse.getLastRow(); else return 0; } public Collection getInspections() { if (activeSynapse != null) return activeSynapse.Inspections(); else return null; } public int numColumns() { if (activeSynapse != null) return activeSynapse.numColumns(); else return 0; } public String getAdvancedColumnSelector() { if (activeSynapse != null) return activeSynapse.getAdvancedColumnSelector(); else return ""; } }
Java
package org.joone.io; import java.beans.*; public class JDBCInputSynapseBeanInfo extends SimpleBeanInfo { // Bean descriptor //GEN-FIRST:BeanDescriptor /*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor(){ BeanDescriptor beanDescriptor = new BeanDescriptor ( JDBCInputSynapse.class , null );//GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; }//GEN-LAST:BeanDescriptor // Property identifiers //GEN-FIRST:Properties private static final int PROPERTY_advancedColumnSelector = 0; private static final int PROPERTY_buffered = 1; private static final int PROPERTY_dbURL = 2; private static final int PROPERTY_driverName = 3; private static final int PROPERTY_enabled = 4; private static final int PROPERTY_firstRow = 5; private static final int PROPERTY_inputPatterns = 6; private static final int PROPERTY_lastRow = 7; private static final int PROPERTY_maxBufSize = 8; private static final int PROPERTY_monitor = 9; private static final int PROPERTY_name = 10; private static final int PROPERTY_plugIn = 11; private static final int PROPERTY_SQLQuery = 12; private static final int PROPERTY_stepCounter = 13; // Property array /*lazy PropertyDescriptor*/ private static PropertyDescriptor[] getPdescriptor(){ PropertyDescriptor[] properties = new PropertyDescriptor[14]; try { properties[PROPERTY_advancedColumnSelector] = new PropertyDescriptor ( "advancedColumnSelector", JDBCInputSynapse.class, "getAdvancedColumnSelector", "setAdvancedColumnSelector" ); properties[PROPERTY_advancedColumnSelector].setDisplayName ( "Advanced Column Selector" ); properties[PROPERTY_buffered] = new PropertyDescriptor ( "buffered", JDBCInputSynapse.class, "isBuffered", "setBuffered" ); properties[PROPERTY_dbURL] = new PropertyDescriptor ( "dbURL", JDBCInputSynapse.class, "getdbURL", "setdbURL" ); properties[PROPERTY_driverName] = new PropertyDescriptor ( "driverName", JDBCInputSynapse.class, "getdriverName", "setdriverName" ); properties[PROPERTY_enabled] = new PropertyDescriptor ( "enabled", JDBCInputSynapse.class, "isEnabled", "setEnabled" ); properties[PROPERTY_firstRow] = new PropertyDescriptor ( "firstRow", JDBCInputSynapse.class, "getFirstRow", "setFirstRow" ); properties[PROPERTY_inputPatterns] = new PropertyDescriptor ( "inputPatterns", JDBCInputSynapse.class, "getInputPatterns", "setInputPatterns" ); properties[PROPERTY_inputPatterns].setExpert ( true ); properties[PROPERTY_lastRow] = new PropertyDescriptor ( "lastRow", JDBCInputSynapse.class, "getLastRow", "setLastRow" ); properties[PROPERTY_maxBufSize] = new PropertyDescriptor ( "maxBufSize", JDBCInputSynapse.class, "getMaxBufSize", "setMaxBufSize" ); properties[PROPERTY_monitor] = new PropertyDescriptor ( "monitor", JDBCInputSynapse.class, "getMonitor", "setMonitor" ); properties[PROPERTY_monitor].setExpert ( true ); properties[PROPERTY_name] = new PropertyDescriptor ( "name", JDBCInputSynapse.class, "getName", "setName" ); properties[PROPERTY_plugIn] = new PropertyDescriptor ( "plugIn", JDBCInputSynapse.class, "getPlugIn", "setPlugIn" ); properties[PROPERTY_plugIn].setExpert ( true ); properties[PROPERTY_SQLQuery] = new PropertyDescriptor ( "SQLQuery", JDBCInputSynapse.class, "getSQLQuery", "setSQLQuery" ); properties[PROPERTY_stepCounter] = new PropertyDescriptor ( "stepCounter", JDBCInputSynapse.class, "isStepCounter", "setStepCounter" ); } catch( IntrospectionException e) {}//GEN-HEADEREND:Properties // Here you can add code for customizing the properties array. return properties; }//GEN-LAST:Properties // EventSet identifiers//GEN-FIRST:Events // EventSet array /*lazy EventSetDescriptor*/ private static EventSetDescriptor[] getEdescriptor(){ EventSetDescriptor[] eventSets = new EventSetDescriptor[0];//GEN-HEADEREND:Events // Here you can add code for customizing the event sets array. return eventSets; }//GEN-LAST:Events // Method identifiers //GEN-FIRST:Methods // Method array /*lazy MethodDescriptor*/ private static MethodDescriptor[] getMdescriptor(){ MethodDescriptor[] methods = new MethodDescriptor[0];//GEN-HEADEREND:Methods // Here you can add code for customizing the methods array. return methods; }//GEN-LAST:Methods private static final int defaultPropertyIndex = -1;//GEN-BEGIN:Idx private static final int defaultEventIndex = -1;//GEN-END:Idx //GEN-FIRST:Superclass // Here you can add code for customizing the Superclass BeanInfo. //GEN-LAST:Superclass /** * Gets the bean's <code>BeanDescriptor</code>s. * * @return BeanDescriptor describing the editable * properties of this bean. May return null if the * information should be obtained by automatic analysis. */ public BeanDescriptor getBeanDescriptor() { return getBdescriptor(); } /** * Gets the bean's <code>PropertyDescriptor</code>s. * * @return An array of PropertyDescriptors describing the editable * properties supported by this bean. May return null if the * information should be obtained by automatic analysis. * <p> * If a property is indexed, then its entry in the result array will * belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. * A client of getPropertyDescriptors can use "instanceof" to check * if a given PropertyDescriptor is an IndexedPropertyDescriptor. */ public PropertyDescriptor[] getPropertyDescriptors() { return getPdescriptor(); } /** * Gets the bean's <code>EventSetDescriptor</code>s. * * @return An array of EventSetDescriptors describing the kinds of * events fired by this bean. May return null if the information * should be obtained by automatic analysis. */ public EventSetDescriptor[] getEventSetDescriptors() { return getEdescriptor(); } /** * Gets the bean's <code>MethodDescriptor</code>s. * * @return An array of MethodDescriptors describing the methods * implemented by this bean. May return null if the information * should be obtained by automatic analysis. */ public MethodDescriptor[] getMethodDescriptors() { return getMdescriptor(); } /** * A bean may have a "default" property that is the property that will * mostly commonly be initially chosen for update by human's who are * customizing the bean. * @return Index of default property in the PropertyDescriptor array * returned by getPropertyDescriptors. * <P> Returns -1 if there is no default property. */ public int getDefaultPropertyIndex() { return defaultPropertyIndex; } /** * A bean may have a "default" event that is the event that will * mostly commonly be used by human's when using the bean. * @return Index of default event in the EventSetDescriptor array * returned by getEventSetDescriptors. * <P> Returns -1 if there is no default event. */ public int getDefaultEventIndex() { return defaultEventIndex; } }
Java
package info.bond.rp.experiments; /** * @author Andrey Bondarenko * * Pair of values needed for generator - maximum index value * for parameter and current one, plus functionality for iteration on values. */ public class MaxValueIndexPair { private Integer valueIndex; private Integer maxValueIndex; // Constructor public MaxValueIndexPair(Integer maxValueIndex, Integer valueIndex) { super(); this.maxValueIndex = maxValueIndex; this.valueIndex = valueIndex; } public MaxValueIndexPair(Integer maxValueIndex) { this(maxValueIndex, 0); } // Business methods public Boolean isLastIndex() { return valueIndex.equals(maxValueIndex - 1); } public void increaseValueIndex() { if (isLastIndex()) { throw new IllegalArgumentException("Cannot increase valueIndex, because it is last!"); } valueIndex++; } public void resetValueIndex() { valueIndex = 0; } // Getters/Setters public Integer getValueIndex() { return valueIndex; } public void setValueIndex(Integer valueIndex) { this.valueIndex = valueIndex; } public Integer getMaxValueIndex() { return maxValueIndex; } public void setMaxValueIndex(Integer maxValueIndex) { this.maxValueIndex = maxValueIndex; } }
Java
package info.bond.rp.experiments; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "info.bond.rp.experiments"; // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
Java
package info.bond.rp.experiments; public class CombinationsGenerator { private MaxValueIndexPair[] indexes; public CombinationsGenerator(Integer[] maxCountOfValuesArray) { int length = maxCountOfValuesArray.length; this.indexes = new MaxValueIndexPair[length]; for (int i = 0; i < length; i++) { Integer maxCountOfValue = maxCountOfValuesArray[i]; MaxValueIndexPair maxValueIndexPair = new MaxValueIndexPair(maxCountOfValue); indexes[i] = maxValueIndexPair; } } public Integer[] getCombination() { int length = indexes.length; Integer[] combinationIndexes = new Integer[length]; for (int i = 0; i < length; i++) { MaxValueIndexPair maxValueIndexPair = indexes[i]; Integer valueIndex = maxValueIndexPair.getValueIndex(); combinationIndexes[i] = valueIndex; } return combinationIndexes; } public void generateNextCombination() { int length = indexes.length; int column = 0; while (column < length) { MaxValueIndexPair maxValueIndexPair = indexes[column]; if (!maxValueIndexPair.isLastIndex()) { maxValueIndexPair.increaseValueIndex(); break; } else { maxValueIndexPair.resetValueIndex(); } column++; } } /** * Returns true when last combination is remaining * * @return */ public Boolean isLast() { Boolean isLast = Boolean.FALSE; int length = indexes.length; MaxValueIndexPair lastValueIndexPair = indexes[length-1]; Integer valueIndex = lastValueIndexPair.getValueIndex(); Integer maxValueIndex = lastValueIndexPair.getMaxValueIndex(); if (valueIndex.equals(maxValueIndex)) { isLast = Boolean.TRUE; } return isLast; } }
Java
package info.bond.rp.experiments; import info.bondtnt.labs.model.research.BoundedDoubleParameter; import info.bondtnt.labs.model.research.NamedDoubleParameter; import info.bondtnt.labs.model.research.ParametersList; import info.bondtnt.labs.model.research.ResearchFactory; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.common.util.EList; public class ExperimentsDataGeneratorImpl implements ExperimentsDataGenerator { private List<BoundedDoubleParameter> boundedDoubleParameterList; public ExperimentsDataGeneratorImpl() { this.boundedDoubleParameterList = new ArrayList<BoundedDoubleParameter>(); } @Override public void add(BoundedDoubleParameter boundedParam) { boundedDoubleParameterList.add(boundedParam); } @Override public List<ParametersList<NamedDoubleParameter>> generateParametersList() { List<ParametersList<NamedDoubleParameter>> resultingList = new ArrayList<ParametersList<NamedDoubleParameter>>(); List<EList<Double>> allValuesList = new ArrayList<EList<Double>>(); List<Integer> indexesList = new ArrayList<Integer>(); int totalCountOfParamsCombinations = 1; for (BoundedDoubleParameter boundedDoubleParameter : boundedDoubleParameterList) { Integer countOfValues = boundedDoubleParameter.countOfValues(); totalCountOfParamsCombinations = totalCountOfParamsCombinations * countOfValues; EList<Double> allValues = boundedDoubleParameter.allValues(); allValuesList.add(allValues); indexesList.add(0); } while (totalCountOfParamsCombinations > 0) { totalCountOfParamsCombinations--; // collect all param values to resultingList ParametersList<NamedDoubleParameter> parametersList = ResearchFactory.eINSTANCE.createParametersList(); for (int i = 0; i < allValuesList.size(); i++) { // for (Integer index : indexesList) { EList<Double> list = allValuesList.get(i); Integer index = indexesList.get(i); Double value = list.get(index); NamedDoubleParameter namedParam = ResearchFactory.eINSTANCE.createNamedDoubleParameter(); // namedParam.setName(name); namedParam.setValue(value); parametersList.addParameter(namedParam ); } int indexOfParam = 0; BoundedDoubleParameter boundedDoubleParameter = boundedDoubleParameterList.get(indexOfParam); Integer countOfValues = boundedDoubleParameter.countOfValues(); totalCountOfParamsCombinations = totalCountOfParamsCombinations * countOfValues; } return null; } }
Java
package info.bond.rp.experiments; import info.bondtnt.labs.model.research.BoundedDoubleParameter; import info.bondtnt.labs.model.research.NamedDoubleParameter; import info.bondtnt.labs.model.research.ParametersList; import java.util.List; public interface ExperimentsDataGenerator { void add(BoundedDoubleParameter boundedParam); List<ParametersList<NamedDoubleParameter>> generateParametersList(); }
Java
package info.bond.rp.experiments; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(org.junit.runners.Suite.class) @Suite.SuiteClasses({ CombinationsGeneratorTest.class, ExperimentsDataGeneratorTest.class, MaxValueIndexPairTest.class }) public class ExperimentsTestsSuite { // the class remains completely empty, // being used only as a holder for the above annotations }
Java
package lv.bond.science.nnstudio; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { private static final String PERSPECTIVE_ID = "nnstudio.perspective"; public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public String getInitialWindowPerspectiveId() { return PERSPECTIVE_ID; } }
Java
package lv.bond.science.nnstudio; import org.eclipse.ui.plugin.*; import org.eclipse.jface.resource.ImageDescriptor; import org.osgi.framework.BundleContext; /** * The main plugin class to be used in the desktop. */ public class Activator extends AbstractUIPlugin { //The shared instance. private static Activator plugin; /** * The constructor. */ public Activator() { plugin = this; } /** * This method is called upon plug-in activation */ public void start(BundleContext context) throws Exception { super.start(context); } /** * This method is called when the plug-in is stopped */ public void stop(BundleContext context) throws Exception { super.stop(context); plugin = null; } /** * Returns the shared instance. * * @return the shared instance. */ public static Activator getDefault() { return plugin; } /** * Returns an image descriptor for the image file at the given * plug-in relative path. * * @param path the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return AbstractUIPlugin.imageDescriptorFromPlugin("nnstudio", path); } }
Java